核心类:private ViewDragHelper mViewDragHelper;
参考:Android群英传
public class DragViewGoup extends FrameLayout {
private ViewDragHelper mViewDragHelper;
private View mMenuView;
private View mMainView;
private int mWidth;
public DragViewGoup(Context context) {
super(context);
initView();
}
public DragViewGoup(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public DragViewGoup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mMenuView = getChildAt(0);
mMainView = getChildAt(1);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = mMenuView.getMeasuredWidth();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return mViewDragHelper.shouldInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mViewDragHelper.processTouchEvent(event);
return true;
}
private void initView() {
mViewDragHelper = ViewDragHelper.create(this, callback);
}
private ViewDragHelper.Callback callback =
new ViewDragHelper.Callback() {
@Override
public boolean tryCaptureView(@NonNull View child, int pointerId) {
return mMainView == child;
}
@Override
public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
return 0;
}
@Override
public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) {
//设置只左右滑动
return left;
}
@Override
public void onViewReleased(@NonNull View releasedChild, float xvel, float yvel) {
super.onViewReleased(releasedChild, xvel, yvel);
if (mMainView.getLeft() < 500) {
mViewDragHelper.smoothSlideViewTo(mMainView, 0,0);
ViewCompat.postInvalidateOnAnimation(DragViewGoup.this);
} else {
mViewDragHelper.smoothSlideViewTo(mMainView, 300, 0);
ViewCompat.postInvalidateOnAnimation(DragViewGoup.this);
}
}
};
@Override
public void computeScroll() {
if (mViewDragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
}
网友评论