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;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);btn = (Button) findViewById(R.id.btn);btn.setOnTouchListener(this);}@Overridepublic 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://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.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>


运行结果:

结果说明:

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

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

总结:

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

参考推荐:

Android 获取屏幕尺寸与密度

Android的计量单位px,in,mm,pt,dp,dip,sp

Bitmap 之 getPixels() 的 stride

更多相关文章

  1. android整合--屏幕旋转触发事件
  2. Android 实现由下至上弹出并位于屏幕底部的提示框
  3. Android屏幕横屏竖屏切换的方法
  4. android 屏幕保持唤醒 不锁屏 android.permission.WAKE_LOCK
  5. Android 屏幕真实分辨率获取
  6. Android 图片左上角、右上角标签tag
  7. Android GPS 获得 经纬度 并得到该 坐标 精确地址

随机推荐

  1. 监听屏幕旋转事件
  2. Android(安卓)SDL移植版学习笔记
  3. android中的汉字转拼音
  4. Windows 8(64位)如何搭建 Android(安卓)
  5. android学习3 进度条
  6. android 上下抽屉拖拽+动画完美实现
  7. android分页处理-3
  8. [Android(安卓)Pro] ant 编译android工程
  9. Android中短信拦截解决方案
  10. android view holder 优化