简单进阶随手指移动的View

因为公司新开项目,好久没空更新博客,今天稍微练练手写了一个简单的小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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值