Android开发中MotionEvent坐标获取方法分析

2019-12-10 19:07:39刘景俊
易采站长站为您分析Android开发中MotionEvent坐标获取方法,结合实例形式分析了MotionEvent获取坐标的相关函数使用方法与相关注意事项,需要的朋友可以参考下  

本文实例讲述了Android开发中MotionEvent坐标获取方法。,具体如下:

Android MotionEvent中getX()与getRawX()都是获取屏幕坐标(横),但二者又有区别
getX()           :   是获取相对当前控件(View)的坐标
getRawX()   :   是获取相对显示屏幕左上角的坐标

演示示例代码

Java代码:

public class MainActivity extends Activity implements OnTouchListener {
  private Button btn;
  private int x = 0, y = 0;
  private int rawX = 0, rawY = 0;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    btn = (Button) findViewById(R.id.btn);
    btn.setOnTouchListener(this);
  }
  @Override
  public boolean onTouch(View view, MotionEvent event) {
    int eventaction = event.getAction();
    switch (eventaction) {
    case MotionEvent.ACTION_DOWN:
      break;
    case MotionEvent.ACTION_MOVE:
      x = (int) event.getX();
      y = (int) event.getY();
      rawX = (int) event.getRawX();
      rawY = (int) event.getRawY();
      Log.e("homer", "x = " + x + "; y = " + y + "; rawX = " + rawX + "; rawY = " + rawY);
      break;
    case MotionEvent.ACTION_UP:
      break;
    }
    return false;
  }
}

xml 代码:

<RelativeLayout xmlns:android="http://www.easck.com/apk/res/android"
  xmlns:tools="http://www.easck.com/tools"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  tools:context=".MainActivity" >
  <TextView
    android:id="@+id/txt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world" />
  <Button
    android:id="@+id/btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/txt"
    android:layout_centerInParent="true"
    android:text="button me" />
</RelativeLayout>