android 自定义View ,跟随手指滑动

为方便内部嵌套,这里选择重写ConstraintLayout,换成其他控件也可以

public class FollowConstraintLayout extends ConstraintLayout {

    //移动
    private GestureDetector gestureDetector;
    private OnClickListener l;
    public FollowConstraintLayout(Context context) {
        super(context);
    }

    public FollowConstraintLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FollowConstraintLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    {
        performClick();
        gestureDetector = new GestureDetector(getContext(),new GestureDetector.SimpleOnGestureListener(){

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                //滑动事件
                setX(e2.getRawX()-(getWidth()+e1.getX())/2);
                setY(e2.getRawY()-(getHeight()+e1.getY())/2);
                return true;
            }

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                //点击事件
                if(l != null)
                    l.onClick(FollowConstraintLayout.this);
                return true;
            }
        });
    }

    @Override
    public void setOnClickListener(@Nullable OnClickListener l) {
       this.l = l;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        gestureDetector.onTouchEvent(event);;
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/jingzz1/article/details/105323359