欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

短视频平台开发android 自定义View ,跟随手指滑动

程序员文章站 2022-06-09 10:27:34
...
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;
    }
}