Android MotionEvent中getX()和getRawX()的区别

vktz3702 9年前

来自: http://www.jcodecraeer.com//a/anzhuokaifa/androidkaifa/2014/0730/1637.html


RawX,RawY 相对于屏幕位置坐标
X,Y 相对于容器的位置坐标

测试代码:

public class Res extends Activity implements View.OnTouchListener {  Button btn = null;  int x = 0;  int y = 0;  int rawx = 0;  int rawy = 0;  @Override  public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.main);  btn = (Button) findViewById(R.id.button);  btn.setOnTouchListener(this);  }  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.d("DEBUG", "getX=" + x + "getY=" + y + "\n" + "getRawX=" + rawx  + "getRawY=" + rawy + "\n");  break;  case MotionEvent.ACTION_UP:  break;  }  return false;  }  }


总结:

getX()是表示Widget相对于自身左上角的x坐标
而getRawX()是表示相对于屏幕左上角的x坐标值(注意:这个屏幕左上角是手机屏幕左上角,不管activity是否有titleBar或是否全屏幕),getY(),getRawY()一样的道理