第17天 Android(安卓)Touch事件学习 4 获取手指触摸位置
16lz
2021-01-24
触摸事件学习系列文章详见:
《Android Touch事件学习系列汇总》
还是回到onTouchEvent方法传递的参数MotionEvent类,其对象有四个方法可以获取当前手指在屏幕上的位置信息,但是一个是相对地址一个是绝对地址,以下具体看下区别。
一、Android Touch事件rawX,rawY与x,y的区别
MotionEvent有四个方法getRawX(), event.getRawY(), getX(),getY(), 为什么同样是x,y轴干嘛非得用两个变量呢?
先来看下效果图:
从上图可以看出来
rawX 和 rawY分别是中间触摸点以屏幕左上角为0,0的相对位置,rawX = 223 说明里触摸点离屏幕最左侧的距离是223
x 和 y 分别是触摸点以灰色区域左上角为0,0的相对位置,x = 96 说明是触摸点离灰色区域最左侧的距离是96
rawX , rawY 相对于屏幕的坐标
x,y 相对于当前控件的坐标
rawX, X 向右移动都是增大,向左移动都是减小
rawY, Y 向下移动都是增大,向上移动都是减小
二、效果图对应代码
1. 中间的灰色区域是一个自定义TextView,用于监听Touch事件,里面有一个LogListener接口,用于在Actvity中实时Touch位置输出信息
public class CustomTextView extends TextView {private LogListener mLogListener;public CustomTextView(Context context) {super(context);}public CustomTextView(Context context, AttributeSet attrs) {super(context, attrs);}public CustomTextView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);}public void setLogListener(LogListener pListener) {mLogListener = pListener;}@Overridepublic boolean onTouchEvent(MotionEvent event) {int action = event.getAction();switch (action) {case MotionEvent.ACTION_MOVE:float rawX = event.getRawX();float rawY = event.getRawY();float x = event.getX();float y = event.getY();if (mLogListener != null) {mLogListener.output("rawX = " + rawX + "\n rawY = " + rawY+ "\n x = " + x+ "\n Y = " + y);}break;}return true;}/** * 用于在Actvity中实时Touch位置输出信息 */public interface LogListener {public void output(String pOutput);}}
2. 在AndroidManifast.xml中配置布局
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:id="@+id/mainlayout"> <TextView android:id="@+id/output" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <demo.touch.CustomTextView android:id="@+id/custom_textview" android:layout_width="150dip" android:layout_height="150dip" android:layout_gravity="center_horizontal" android:background="#666666"/> </LinearLayout>
3. Activity中加载视图,控制显示touch位置信息
public class TouchDemoActivity extends Activity {private TextView mOutput;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);mOutput = (TextView) findViewById(R.id.output);mOutput.setText("rawX = 0 \n rawY = 0 \n x = 0 \n Y = 0");CustomTextView customTextView = (CustomTextView) findViewById(R.id.custom_textview);customTextView.setLogListener(new CustomLogListener());}/** * 用于获取TouchEvent中位置信息 */private class CustomLogListener implements LogListener {@Overridepublic void output(String pOutput) {mOutput.setText( pOutput );}}}
三、源码下载
例子下载
更多相关文章
- Android(安卓)Wifi模块学习
- android 处理生命周期事件
- 如果我是Android面试官九
- Android实践之ScrollView中滑动冲突处理
- 修正AppCompatSpinner弹出框位置问题
- 使用线程更新UI
- Android(安卓)SDK Manager无法显示可供下载的未安装SDK解决方案
- android 静默安装,含获取各种应用信息方法,根据apk获取应用信息
- 深入Android开发之--Android事件模型