MotionEvent.getRawX(),getRawY及getX(),getY()和View.getX(),getY()区别
RawX和X区别
1、
MotionEvent.getRawX()和
MotionEvent.getRawY() MotionEvent.getRawX(),表示当前触摸点离屏幕左上角的x轴距离 MotionEvent.getRawY(),表示当前触摸点离屏幕左上角的y轴距离 |
2、
MotionEvent.getX()和
MotionEvent.getY() MotionEvent.getX(),代表当前触摸点到当前触摸的组件左上角的x轴距离 MotionEvent.getY(),代表当前触摸点到当前触摸组件左上角的y轴距离 |
3、View.getX()和View.getY() View.getX(),代表的是当前组件到屏幕的左边的距离,也就是left View.getY(),代表的是当前组件到屏幕的上边的距离,也就是top |
图解: 注意:其中的event.getRawY()和View.getY(),箭头应该指向屏幕的顶端。 |
代码: package cn.zengfansheng.day08.rawx_x;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import cn.zengfansheng.day08.R;
public class RawXActivity extends Activity {
private Button btnTouch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rawx_x);
btnTouch = (Button) this.findViewById(R.id.bt_touch);
btnTouch.setOnTouchListener(new OnTouchListener() {
@SuppressLint("NewApi")
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
System.out.println("touch down...");
float rawX = event.getRawX();
float rawY = event.getRawY();
System.out.println("event.rawX=" + rawX + "event.rawY=" + rawY);
float x = event.getX();
float y = event.getY();
System.out.println("event.x=" + x + " event.y=" + y);
float x2 = v.getX();
float y2 = v.getY();
System.out.println("view.x=" + x2 + " view.y=" + y2);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
});
}
} |
结果: |