这篇文章主要介绍了Android开发中MotionEvent坐标获取方法,结合实例形式分析了MotionEvent获取坐标的相关函数使用方法与相关注意事项,需要的朋友可以参考下
这篇文章主要介绍了Android开发中MotionEvent坐标获取方法,结合实例形式分析了MotionEvent获取坐标的相关函数使用方法与相关注意事项,需要的朋友可以参考下
这篇文章主要介绍了Android开发中MotionEvent坐标获取方法,结合实例形式分析了MotionEvent获取坐标的相关函数使用方法与相关注意事项,需要的朋友可以参考下
本文实例讲述了android开发中motionevent坐标获取方法。分享给大家供大家参考,具体如下:
android motionevent中getx()与getrawx()都是获取屏幕坐标(横),但二者又有区别
getx() : 是获取相对当前控件(view)的坐标
getrawx() : 是获取相对显示屏幕左上角的坐标
演示示例代码
java代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
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 代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<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程序设计有所帮助。
发表评论