繁体   English   中英

获取MotionEvent在ButtonView中的相对位置

[英]Getting relative position of a MotionEvent inside a buttonView

在此处输入图片说明

private void buttonTouch(MotionEvent event, int num) {
    Log.v(TAG, num +" Button Click : X" + event.getX() + " Y:" +event.getY());
}

如果红色正方形是按钮视图,并且用户单击它,则event.getX()似乎会产生有关单击相对于绿松石色域甚至整个屏幕的相对值。 有一种简单的方法可以使点击位于红色方框内吗?

我看到有用于获取按钮高度和宽度的函数,但是我没有看到可以使框的边缘之一或另一种了解按钮确切位置的函数,因此我可以使用该函数计算点击相对于按钮的位置。

我已经测试了这段代码,它获取了相对于自己的视图(一个按钮)的坐标。

我添加了一种方法来检索屏幕的宽度和高度,以获取全局参考。

//活动

public class TestActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_activity);

        Button bt_test = (Button) findViewById(R.id.bt_test_1);
        bt_test.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent event) {
                Log.v("TAG_TOUCH", " Button Click: X " + event.getX() + " Y: " + event.getY());
                Point point = getSizeScreen();
                Log.v("TAG_SIZE_SCREEN", " Width: " + point.x + " Height: " + point.y);
                return true;
            }
        });

        Button bt_test_2 = (Button) findViewById(R.id.bt_test_2);
        bt_test_2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent event) {
                Log.v("TAG_TOUCH", " Button Click: X " + event.getX() + " Y: " + event.getY());
                Point point = getSizeScreen();
                Log.v("TAG_SIZE_SCREEN", " Width: " + point.x + " Height: " + point.y);
                return true;
            }
        });


    }

    private Point getSizeScreen() {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        return size;
    }

}

//布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    android:orientation="horizontal"
    android:weightSum="2">

    <Button
        android:id="@+id/bt_test_1"
        android:layout_width="0dp"
        android:layout_height="300dp"
        android:layout_margin="10dp"
        android:layout_weight="1"
        android:background="#000000" />

    <Button
        android:id="@+id/bt_test_2"
        android:layout_width="0dp"
        android:layout_height="300dp"
        android:layout_margin="10dp"
        android:layout_weight="1"
        android:background="#000000" />

</LinearLayout>

暂无
暂无

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

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