手机
当前位置:查字典教程网 >编程开发 >安卓软件开发 >Android开发中MotionEvent坐标获取方法分析
Android开发中MotionEvent坐标获取方法分析
摘要:本文实例讲述了Android开发中MotionEvent坐标获取方法。分享给大家供大家参考,具体如下:AndroidMotionEvent中...

本文实例讲述了Android开发中MotionEvent坐标获取方法。分享给大家供大家参考,具体如下:

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; @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 代码:

<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>

运行结果:

Android开发中MotionEvent坐标获取方法分析1

点击屏幕中间的Button,获取的坐标信息:

Android开发中MotionEvent坐标获取方法分析2

结果说明:

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

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

总结:

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

希望本文所述对大家Android程序设计有所帮助。

【Android开发中MotionEvent坐标获取方法分析】相关文章:

Android中ActionBar以及menu的代码设置样式

Android 开发中需要注意到的小细节

Android中3种图片压缩处理方法

Android中使用sax解析xml文件的方法

Android开发之BroadcastReceiver用法实例分析

Android开发: fragment解析及案例

Android应用开发SharedPreferences存储数据的使用方法

Android从服务器端获取数据的几种方法

Android三种菜单实例分析

android中知道图片name时获取图片的简单方法

精品推荐
分类导航