简单进阶随手指移动的View

来源:互联网 发布:南风知我意2txt书包网 编辑:程序博客网 时间:2024/04/29 17:06

因为公司新开项目,好久没空更新博客,今天稍微练练手写了一个简单的小Demo,手指移动View。是很简单,所谓难点只是需要清楚控件TouchEvent的几个Action的了解及控件位置X坐标Y坐标和偏移量的计算。

我们自定义一个class 继承View ,然后重写onTouchEvent方法,看下代码:

@Override    public boolean onTouchEvent(MotionEvent event) {        int x = (int) event.getX();        int y = (int) event.getY();        switch (event.getAction()){            case MotionEvent.ACTION_DOWN://监听手指按下的动作                lastX = x;//记录刚按下屏幕的x坐标                lastY = y;//记录刚按下屏幕的y坐标                break;            case MotionEvent.ACTION_MOVE://监听手指移动的动作                int offsetX = x - lastX;//算出x轴的偏移量                int offsetY = y - lastY;//算出y轴的偏移量                layout(getLeft()+offsetX,getTop()+offsetY,getRight()+offsetX,getBottom()+offsetY);//根据偏移量重新定位View的位置                break;        }        return true;    }

完整的代码如下:

public class CustomView extends View {    private static final String TAG = "CustomView";    private int lastX;    private int lastY;    public CustomView(Context context) {        super(context);    }    public CustomView(Context context, @Nullable AttributeSet attrs) {        super(context, attrs);    }    @Override    public boolean onTouchEvent(MotionEvent event) {        int x = (int) event.getX();        int y = (int) event.getY();        switch (event.getAction()){            case MotionEvent.ACTION_DOWN://监听手指按下的动作                lastX = x;//记录刚按下屏幕的x坐标                lastY = y;//记录刚按下屏幕的y坐标                break;            case MotionEvent.ACTION_MOVE://监听手指移动的动作                int offsetX = x - lastX;//算出x轴的偏移量                int offsetY = y - lastY;//算出y轴的偏移量                layout(getLeft()+offsetX,getTop()+offsetY,getRight()+offsetX,getBottom()+offsetY);//根据偏移量重新定位View的位置                break;        }        return true;    }}

该有的注释已经注释上去了。

我们直接在布局文件引用上这个控件:

<?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"    tools:context="com.jstacc.energy.blogtest.MainActivity">    <com.blogtest.CustomView        android:layout_width="50dp"        android:layout_height="50dp"        android:background="@color/colorPrimary"/></android.support.constraint.ConstraintLayout>


看下效果:






阅读全文
0 0