简体   繁体   English

我可以得到我点击位置的坐标xy吗? OnTapListener?

[英]Can I get coordinates x y of the position where I tap? OnTapListener?

I've been searching for some function that can give me x,y coordinates of the the point where I touch on screen. 我一直在寻找可以给我x,y坐标的函数,该坐标是我在屏幕上触摸的点。 I got a code of onTouch() but couldn't find a way to call that function. 我得到了onTouch()的代码,但是找不到调用该函数的方法。

public boolean onTouch(View v, MotionEvent event) {
   int x = event.getX();
   int y = event.getY();
   return true;
}

What is View and MotionEvent that I'm supposed to pass in arguements? 我应该在争论中传递的View和MotionEvent是什么? Can anyone please help me and tell me how to get just x,y of the point of touch? 谁能帮我一下,告诉我如何只获得x,y的接触点?

Try this for a view: 尝试以下视图:

View yourView = findViewById(R.id.yourViewId)
    yourView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getActionMasked() == MotionEvent.ACTION_DOWN) {
            // Do something
            x = event.getX();
            y = event.getY();
            }
            return true;
        }
    });

or Try this for an activity: 或尝试以下活动:

@Override
public boolean onTouchEvent(MotionEvent event) {
            if(event.getActionMasked() == MotionEvent.ACTION_DOWN) {
            // Do something
            x = event.getX();
            y = event.getY();
            }
            return true;
}

By the way, you don't need to call this method, you just override it and any time the screen is touched, this method will be called by your activity. 顺便说一句,您不需要调用此方法,只需重写它,并且每当触摸屏幕时,您的活动都会调用此方法。

Let me know if this doesn't work and I'll delete the answer 让我知道这是否无效,我将删除答案

To get the coordinates for when you press try: 要获取按下时的坐标,请尝试:

switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN: // when you touch
        x = event.getRawX(); // gather x and y
        y = event.getRawY();
        break;

PS I would comment but have too low rep PSS you if statement if this is all you want to do, switch if your trying to do multiple things ie dragging an item. PS我会发表评论,但代表PSS太低,如果您声明这是您要做的一切,请尝试切换,如果您尝试做多件事(即拖动一个项目),请切换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM