短视频平台开发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;
}
}