MotionEvent的理解

来源:互联网 发布:windows上类似imovie 编辑:程序博客网 时间:2024/06/13 00:35

MotionEvent的理解

    今天初步学习了MotionEvent,做了一个简单的小程序:界面如下:触摸点击移动图标,能改变图标的位置,动作包括down---move---up(这个暂时没用到)


下面介绍一下流程:

1、得到图标相对于父视图(即整个屏幕)的x,y坐标:


eventx=event.getRawx()

eventy=event.getRawy()

2,进行down这个动作时,要记录下此时图标的x,y坐标

lastx=eventx;

lasty=eventy;

3、进行move这个动作时,要记录下来图标x,y坐标改变了多少,同时得到图标的左,上,右,下的x,y坐标,使用layout(left,top,right,botton)方法使结束move这个动作时图标在结束的这个位置上。

dx=eventx-lastx;
dy=eventy-lasty;
left=iv.getleft()+dx;
top = iv.gettop()+dy;
right=iv.getright()+dx;
bottom=iv.getbottom()+dy;
iv.layout(left,top,right,bottom);

4 需要注意的一点是:我们要控制图标不能移出屏幕:

首先我们要得到整个屏幕的高和宽:

int maxb=cl_main.getBottom();//得到整个屏幕的高
int maxr=cl_main.getRight();//得到整个屏幕的宽

其次判断图标的左,上,右,下的x,y坐标是否超出了屏幕:

if(left<0){
right+=-left;
left=0;
}
if(top<0){
bottom+=-top;
top=0;
}
if(right>maxr){
left-=right-maxr;
right=maxr;
}
if(bottom>maxb){
top-=bottom-maxb;
bottom=maxb;
}

下图是界面视图:



界面布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/cl_main"
tools:context="com.example.sxy.app06.MainActivity">

<
ImageView
android:id="@+id/iv_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</
android.support.constraint.ConstraintLayout>

代码如下

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int eventx= (int) motionEvent.getRawX();//得到ImageView相对于父视图的x坐标
int eventy= (int) motionEvent.getRawY();//得到ImageView相对于父视图的y坐标
int maxb=cl_main.getBottom();//得到整个视图的高
int maxr=cl_main.getRight();//得到整个视图的宽
switch (motionEvent.getAction()) {

case MotionEvent.ACTION_DOWN:
lastx=eventx;
lasty=eventy;


break;
case MotionEvent.ACTION_MOVE:
int dx=eventx-lastx;
int dy=eventy-lasty;
int left=iv_main.getLeft()+dx;
int top=iv_main.getTop()+dy;
int right=iv_main.getRight()+dx;
int bottom = iv_main.getBottom()+dy;
if(left<0){
right+=-left;
left=0;
}
if(top<0){
bottom+=-top;
top=0;
}
if(right>maxr){
left-=right-maxr;
right=maxr;
}
if(bottom>maxb){
top-=bottom-maxb;
bottom=maxb;
}
iv_main.layout(left,top,right,bottom);
lastx=eventx;
lasty=eventy;


break;
}
return true;
}

以上是我今天的学习心得与总结。