Android开发之初级开发_MotionEvent获取屏幕坐标问题

布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:gravity="center" >

    <Button
        android:id="@+id/btn_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="坐标" />

</RelativeLayout>

代码:

public class MainActivity extends Activity implements OnTouchListener
{
    private Button btn_test;
    int testX, testY;
    int rawX, rawY;

    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_test = (Button) findViewById(R.id.btn_test);
        btn_test.setOnTouchListener(this);
    }

    public boolean onTouch(View v, MotionEvent event)
    {
        testX = (int) event.getX();
        testY = (int) event.getY();
        rawX = (int) event.getRawX();
        rawY = (int) event.getRawY();
        Toast.makeText(MainActivity.this, "testX = " + testX + "testY = " + testY + "\n" + "rawX = " + rawX + "rawY = " + rawY, 1).show();
        return false;
    }
}

  结果:

testX,testY  :  分别获取的相对Button控件的坐标 getX(), getY()

rawX,rawY  : 分别获取的相对显示屏幕左上角的坐标 getRawX(), getRawY()

posted @ 2014-07-05 16:12  loneliness__白色  阅读(326)  评论(0)    收藏  举报