android - 当我触摸一个按钮时,如何获得触摸相对于整个 View 的 x/y 位置?

标签 android touch ontouchlistener motionevent

我想要与整个屏幕相关的触摸信息,但我得到的是与按钮相关的触摸信息。

ButtonTouchListener = new OnTouchListener(){

    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
             switch(v.getId()){
                case R.id.somebutton
                          //do things
                    //....etc
            }

           int action = event.getAction();
       switch(action){
       case MotionEvent.ACTION_UP:
         act += event.toString();
         System.out.println("release: " + act);
}};

我从事件中得到的 x 和 y 与按钮有关(0、0 是按钮的角,而不是屏幕的角)。如何仅在按下按钮时获取相对于整个屏幕的 x 和 y 位置?

最佳答案

要获得相对于 View 的触摸位置,请将触摸事件的 (x,y) 添加到按钮的 (x,y);要获得按钮相对于其父级(您的 View )的位置,请使用 getLeft()getTop() 方法。

documentation对于 ViewPosition 下有以下内容:

It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.

onTouch 方法的示例代码:

float screenX = v.getLeft() + event.getX();   // X in Screen Coordinates
float screenY = v.getTop() + event.getY();    // Y in Screen Coordinates

关于android - 当我触摸一个按钮时,如何获得触摸相对于整个 View 的 x/y 位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19615596/

相关文章:

android - Android 上的 JavaFx WebView 组件

Objective-C SpriteKit 创建到某些点的虚线

android - 如何检测按钮背景资源(可绘制)android?

android - 同一个触摸监听器被多次调用

Java Lang 空指针异常,但我不明白为什么?

java - Android - 动态创建 View 无法按预期工作

java - 覆盖未在 Android 中调用的方法

javascript - CSS :hover/:focus vs click event on (mobile) touch devices

javascript - jquery 将如何为移动设备实现触摸事件?

android - OnTouchListener,ACTION_UP 在 30 秒超时后自动触发