Android MotionEvent 坐标获取
来源:互联网 发布:高频批量交易算法 编辑:程序博客网 时间:2024/06/05 05:23
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>
运行结果:
点击屏幕中间的Button,获取的坐标信息:
结果说明:
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
- Android MotionEvent 坐标获取
- Android MotionEvent 坐标获取
- Android MotionEvent 坐标获取
- View v.getX(), MotionEvent event.getX() 获取坐标区别
- View 和MotionEvent 提供的获取坐标的方法
- Android群英传——第五章常用触控事件MotionEvent与获取View坐标长度的各种方法
- Android 中View坐标和事件传递中MotionEvent方法
- android:MotionEvent
- android:MotionEvent
- android MotionEvent
- android motionevent
- Android MotionEvent
- android MotionEvent
- Android MotionEvent
- android MotionEvent
- android 获取坐标
- android 获取坐标
- Android 获取坐标
- Qt的Event Filter(转)
- wxWidgets的摸索
- PHP中防止SQL注入
- 结构体类型的静态成员
- php 5.2.4 iconv函数TRANSLIT 有时不靠谱
- Android MotionEvent 坐标获取
- android控件之ScrollView
- Qt事件过滤
- 记忆化搜索专题
- 用kms激活 运行OFFICE2010Rearm office 2010出现错误提示 Error: 0xc004fe00
- 精通 Grails 的大侠们 domain 用jointable 设置外键 为什么一直是默认的ID 不能自定义吗?
- 警惕由eAccelerator导致的Apache进程崩溃
- Java--Socket通信(双向)
- 二叉查找树后继节点和前驱节点查找