使用ViewDragHelper需要5個步驟
一、使用靜態(tài)工廠法實例化一個ViewDragHelper對象
/**
* 該方法用于實例化ViewDragHelper對象
*/
private void init() {
mViewDragHelper = ViewDragHelper.create(this, callback); //實例化ViewDragHelper對象
}
二、創(chuàng)建上面使用的callback參數(shù)
該參數(shù)是ViewDragHelper.Callback類型的,這里需要通過匿名內(nèi)部類來重寫至少以下4個方法
private ViewDragHelper.Callback callback = new ViewDragHelper.Callback() {
/**
* 該方法用于捕獲ViewGroup中需要被移動的View。
* @param child
* @param pointerId
* @return 使用判斷來返回需要被ViewDragHelper的子view是哪一個
*/
@Override
1. public boolean tryCaptureView(View child, int pointerId) {
showLog("tryCaptureView()");
return mView0 == child; //捕獲需要拖動的view
}
@Override
2. public int clampViewPositionVertical(View child, int top, int dy) {
showLog("clampViewPositionVertical()");
return 0;
}
/**
* @param child
* @param left 表示系統(tǒng)認為的水平方向需要移動多少
* @param dx 表示水平方向上移動了多少距離
* @return 返回left則跟著手指在水平方向上移動
*/
@Override
3. public int clampViewPositionHorizontal(View child, int left, int dx) {
showLog("left = " + left);
return left;
}
/**
* 該方法會在手指抬起后回調(diào),決定了view的移動。
* @param releasedChild
* @param xvel 表示水平方向的移動速度
* @param yvel 表示垂直方向的移動速度
*/
@Override
4. public void onViewReleased(View releasedChild, float xvel, float yvel) {
showLog("onViewReleased()");
super.onViewReleased(releasedChild, xvel, yvel);
if (mView0.getLeft()<500){
//距離不足,關(guān)閉菜單
mViewDragHelper.smoothSlideViewTo(mView0,0,0); //絲滑的滑動view到(0,0)位置
ViewCompat.postInvalidateOnAnimation(DragHelperView.this); //重繪viewGroup
} else {
//距離足夠,打開菜單
mViewDragHelper.smoothSlideViewTo(mView0,300,0);
ViewCompat.postInvalidateOnAnimation(DragHelperView.this);
}
}
};
三、獲得要操作的View及view的尺寸
/**
* 該方法在填充布局后調(diào)用,用于獲取到布局中的子view。
*/
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mView0 = getChildAt(0);
mView1 = getChildAt(1);
}
/**
* 該方法是為了獲得view的尺寸
* @param w
* @param h
* @param oldw
* @param oldh
*/
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = mView0.getMeasuredWidth(); //獲得view的寬
}
四、重寫computeScroll()方法來實現(xiàn)滑動
這有點像Scroller的使用
@Override
public void computeScroll() {
super.computeScroll();
if (mViewDragHelper.continueSettling(true)){ //判斷view是否在繼續(xù)移動
ViewCompat.postInvalidateOnAnimation(this); //是,刷新重繪viewGroup
}
}
五、攔截觸摸事件,并且交給ViewDragHelper對象處理
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return mViewDragHelper.shouldInterceptTouchEvent(ev); //攔截處理觸摸事件,并傳遞給ViewDragHelper
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mViewDragHelper.processTouchEvent(event); //將觸摸事件傳遞給ViewDragHelper處理
return true;
}
如果你覺得還不錯,那就動動小捶捶敲個關(guān)注、點個贊哦??!