ViewDragHelper的使用

  我19年一全年都沒寫過博客,說實話沒寫的慾望,如今找到了動機,由於我發現讓我願意研究的東西,很大一部分由於它有意思,沒什麼興趣的知識,除非工做須要,真的不肯意碰。今天介紹的是ViewDragHelper這個工具類。它在你自定義viewGroup時,幫你解決子view拖動、定位、狀態跟蹤。這是官方的解釋,固然,我用大白話在複述一下:子view想要自由飛翔,確定得先通過父view的容許,而父view把作決定的權利所有交給了ViewDragHelper。雖然這個helper類代碼很長,有1500多行,但搞清楚了它開放給咱們的幾個回調,以及一丁點對事件分發的理解,就能夠寫出一個讓你成就感滿滿的控件。今天的目標:寫一個右滑就多出兩個子view的控件(大約150行代碼就行)。android

       

  這個例子是仿github上項目寫的,原項目地址https://github.com/daimajia/AndroidSwipeLayout。固然這是精簡版的,別人的代碼老是望而生畏!ViewDragHelper從攔截處處理事件的整個過程,只公佈了一個回調類給咱們使用,咱們能夠從其中選一些對咱們有用的去實現,這裏,我把我寫這個控件實現的類列舉出來:git

public abstract boolean tryCaptureView(@NonNull View child, int pointerId);

1.當你拖動子view,這個方法確定是要實現的,並且必須返回true,表示你要捕獲你拖動的子view,接下來它的位置信息、拖動速度等一系列參數纔會被記錄,並返回給你。github

 

 

public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) {return 0;}

2.前面提過,你捕獲控件後,helper會返回給你一些數據,這個方法返回給你的就是控件水平位置信息。 重點理解left這個值。寫來寫去,就這個left值迷惑人!!!請慢慢品味下面這句話:以child父佈局的左上角頂點爲座標原點,以右爲x軸正方向,下爲y軸正方向, left值等於child水平方向劃過的像素數(從左往右,像素數爲正,反之爲負)與它自身的mLeft值的和。撇開數值的結果,通俗的來說就是你此次移動以後,child的水平位置應該在哪裏!爲何是應該呢,由於這個方法走完,緊接着系統會拿該方法返回值做爲view新的x座標(即mLeft值)。那麼在系統告訴你view移動後,應該所處的位置與你最終返回的位置之間,你能夠作邊界判斷。例如:子view初始位置mLeft = 0,若是我將view向左滑動20px,那麼此方法left就會返回給我-20,而我又不想拿這個值做爲子view的新的x座標。那我返回0,就可讓子view水平還在原位置。如下兩個例子是left值的計算方法:api

  例子1:子view視圖的左頂點就在父佈局的座標原點處,當你手指從左往右滑動10個像素,left就等於像素數+10 加上view距離座標原點橫座標0,結果就是10;app

  例子2:父佈局paddingleft 爲20像素,若是單位是dp,最終也是轉爲px計算的。子view的mleft = 20,當你手指從右往左滑動10個像素,left就等於像素數-10+20=10;ide

  left理解通透以後,dx就好說了,還記得剛提到的可正可負的像素數嗎,哈哈,dx就是它!綜上,能夠得出一個公式:left = view.getLeft()+dx.函數

 

3.clampViewPositionVertical和上一個方法就是雙胞胎兄弟,這個我就很少介紹了。更多的文字留給更神祕的方法。工具

 

 

public void onViewPositionChanged(@NonNull View changedView, int left, int top, int dx, int dy) 

4.這個方法的解釋我以爲直接看源代碼更好理解:佈局

 private void dragTo(int left, int top, int dx, int dy) { int clampedX = left; int clampedY = top; final int oldLeft = mCapturedView.getLeft(); final int oldTop = mCapturedView.getTop(); if (dx != 0) { clampedX = mCallback.clampViewPositionHorizontal(mCapturedView, left, dx); ViewCompat.offsetLeftAndRight(mCapturedView, clampedX - oldLeft); } if (dy != 0) { clampedY = mCallback.clampViewPositionVertical(mCapturedView, top, dy); ViewCompat.offsetTopAndBottom(mCapturedView, clampedY - oldTop); } if (dx != 0 || dy != 0) { final int clampedDx = clampedX - oldLeft; final int clampedDy = clampedY - oldTop; mCallback.onViewPositionChanged(mCapturedView, clampedX, clampedY, clampedDx, clampedDy); } }

  當view被拖動,會調用這個dragTo,這個方法將以上3個方法的執行順序以及參數傳遞,描述的很是清楚,能夠看到onViewPositionChanged()參數中的left,top分別是前兩個方法返回給咱們的,末尾的dx,dy對咱們移動view也有用,待會能夠看到。post

 

 

public void onViewReleased(@NonNull View releasedChild, float xvel, float yvel) {

5.顧名思義,這個方法就是當咱們手指離開view時調用的,xvel ,yvel分別是手指離開view時,view在x,y軸上的速度,這裏的速度是指每秒劃過的像素數。這個方法執行後,假如咱們想讓view恢復至初始位置,就能夠在這裏面調用,根據速度,咱們能夠作些速度判斷,瞭解用戶到底想不想滑動,仍是勻速滑動,埋個伏筆,待會寫控件時,這個方法裏面能夠作些文章。

 

 

public int getViewHorizontalDragRange(@NonNull View child) {}

6.這個函數的使用和子view的點擊事件關聯性很大,同時結合事件分發,才能完整的將子view的點擊事件合理的處理,因此這個方法我在第二篇單獨講它的使用,如今你能夠不重寫它,今天主要目標,讓咱們的控件滑起來!

 

  這幾個回調函數介紹完,看看xml佈局,咱們繼承水平的LinearLayout去實現。

 <com.lq.counter.swipeLayout.MyLinearSwipeLayout android:id="@+id/sample1" android:layout_width="match_parent" android:layout_height="120dp" android:orientation="horizontal">
        <LinearLayout android:id="@+id/bottom_layout" android:background="@mipmap/sceen" android:orientation="horizontal" android:visibility="visible" android:layout_width="match_parent" android:layout_height="match_parent">
        </LinearLayout>

        <LinearLayout android:id="@+id/bottom_wrapper" android:background="#66ddff00" android:layout_width="160dp" android:orientation="horizontal" android:layout_height="match_parent">
            <TextView android:id="@+id/tv1" android:layout_width="80dp" android:layout_height="match_parent" android:text="刪除" android:background="@mipmap/wind"
                />
            <TextView android:layout_width="80dp" android:layout_height="match_parent" android:text="收藏" android:background="@mipmap/kaer"
                />
        </LinearLayout>
    </com.lq.counter.swipeLayout.MyLinearSwipeLayout>

 

  父佈局裏面有兩個子LinearLayout,第一個咱們稱爲surface,它寬度爲match_parent,是可見的佈局,第二個咱們稱爲bottom,它在屏幕以外,是隱藏的佈局(這裏是最基本的概念)。

1.首先在咱們SwipeLayout的構造方法中初始化ViewDragHelper:helper = ViewDragHelper.create(this,callback);

2.準備好5個待會要用的方法:

 

 @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return helper.shouldInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent event) { helper.processTouchEvent(event); return true; } private View getSurfaceView(){ return getChildAt(0); } private View getBottomView(){ return getChildAt(1); } private enum State{ CLOSE, OPEN }

這裏能夠看到將控件的攔截和處理全都放權給了viewDragHelper,固然了,當你遇到子view點擊事件莫名其妙的失效或者產生時,你就要在攔截處理裏面找突破口,不過今天咱們不涉及子view的點擊事件處理,只是爲了完成滑動展現兩個隱藏子view就行。 

 

 3.開始重寫Callback

 private ViewDragHelper.Callback callback = new ViewDragHelper.Callback() { private State state; @Override public boolean tryCaptureView(@NonNull View child, int pointerId) { if (getSurfaceView().getLeft() == 0){ state = State.CLOSE; }else { state = State.OPEN; } return true; } };

注意:getSurfaceView.getLeft==0,這麼寫是基於父佈局paddingleft = 0來寫的,不過沒關係,這裏在捕獲子view時,先記錄了bottomLayout 是展現仍是隱藏的,待會會用到這個狀態。

  接着給兩個子view水平滑動設置邊界:

 @Override public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) { if (child == getSurfaceView()) { if (left > 0) { left = 0; } if (left < -getBottomView().getMeasuredWidth()) { left = -getBottomView().getMeasuredWidth(); } } else { int marleft = getSurfaceView().getMeasuredWidth() - getBottomView().getMeasuredWidth(); if (left < marleft){ left = marleft; } } return left; }

surface有兩處邊界,bittomLayout只有一處邊界,理解他們各自的臨界狀態,能夠經過畫些草圖,看bottomLayout徹底展現和徹底隱藏這兩種極端狀況。

  在回過頭看看上方的dragTo()方法,你會發如今調用了clampViewPositionHorizontal 以後,子view就會移動到新設置好的位置,但有個問題,既然我拖動的子view移動了,另外一個子view卻依舊在原地,怎麼辦,這時

onViewPositionChanged()就能夠解決這個問題,咱們讓另外一個view也跟着移動。
 @Override public void onViewPositionChanged(@NonNull View changedView, int left, int top, int dx, int dy) { if (changedView == getSurfaceView()){ getBottomView().offsetLeftAndRight(dx); }else { getSurfaceView().offsetLeftAndRight(dx); } invalidate(); }

 

 爲何使用dx,我把dragTo的代碼再給你們看一次,並標註了一下,就更清楚了,一個子view移動多少距離,另外一個子view也緊跟着在相同方向移動相同的距離,這樣總體看起來父佈局就整個在滑動:



若是你寫到這裏,其實咱們的view已經能夠滑起來,但你會感受手感欠佳,好比bottomLayout會展現一部分,一部分還在屏幕外,我想快速滑動一小段距離就把整個bottomLayout給展現出來,而不是滑動一整個
隱藏view的寬度才能看到它。對對對!這些都是缺點,接下來,今天介紹的最後一個回調onViewRelased 將解決這些問題。
  
@Override public void onViewReleased(@NonNull View releasedChild, float xvel, float yvel) { float minV = helper.getMinVelocity()*5; float fraction = state == State.CLOSE ? 0.25f:0.75f; if (Math.abs(xvel) > minV){ if (state == State.CLOSE){ if (xvel > 0 ){ close(); }else { open(); } }else { if (xvel >0){ close(); }else { open(); } } }else { //勻速
                if(Math.abs(getSurfaceView().getLeft()) > getBottomView().getMeasuredWidth()*fraction){ open(); }else { close(); } } invalidate(); }
 1.這裏有最小速度閾值,默認是100px/s,我乘以5是爲了下降速度的敏感度。當大於最小速度,咱們能夠認爲用戶快速地滑動了一下,那麼根據當前狀態,能夠分兩組狀況:
    如今是關閉,若是用戶快速右滑,xvel>0,那麼就是關閉,若是左滑呢,那麼就是打開。
    如今是關閉,推理同上。
2.小於最小速度,那麼就是勻速滑動,或慢慢滑動,這時再也不以速度做爲參考標準,而以surfaceLayout滑動的距離與bottomLayout的佔比fraction的大小比較做爲用戶意圖的評判標準。分兩種狀況:
    如今是關閉,此時fraction = 0.25,咱們判斷若是surface的x座標超過了bottomLayout寬度的四分之一,那麼就是打開,固然,咱們此時使用的surface的x的絕對值,而這個值實際上是不會大於0的,
由於在水平移動時,mLeft已經作了邊界處理。
    如今是打開,此時fraction = 0.75;這時surface隱藏在屏幕左邊的區域大小剛好就是bottomLayout整個的寬度,當用戶左滑時,getSuefaceView的橫座標絕對值沒有改變,仍是bottomLayout的
寬度,因此仍是打開,當用戶右滑時,surface的mleft在bottomLayout的寬度比例1.0至0.75區間內,均可以認爲維持現狀,即open,一旦到了[0.75,0]區間,那麼就認爲是關閉。


接下來看open與close的實現:
   private void close(){ helper.smoothSlideViewTo(getSurfaceView(), 0, 0); } private void open(){ helper.smoothSlideViewTo(getSurfaceView(),-getBottomView().getMeasuredWidth(),0); }
 
這兩個方法都調用了smoothSlideViewTo,它的做用就是將你的view平滑地滾動到指定的位置。到了這裏,不知道你是否留意到,我滾動的view都是surfaceLayout,爲何bottomLayout不去也調這個方法,
難道還讓它待在原地嗎,其實,我在open和close後面都加了一行invalidate,它讓咱們的父佈局從新layout一次,你把surfaceLayout移到座標原點處,那麼按照LinearLayout的佈局特徵,它會把另外一個
子view的佈局參數也挪到surfaceLayout後頭。並且,這個方法它自己只是設置好了view的終點位置,真正觸發滾動,還得用invalidate。它的實現跟scroller是相似的,在第一次重繪時,調用computeScroll,
在computeScroll裏面判斷是否已經移到終點,沒有的話接着invalidate,invalidate裏面又會去重繪。。。這樣一直持續下去,直至,computeScroll裏面認定view已經到達終點,就再也不調invalidate。
 @Override public void computeScroll() { if (helper.continueSettling(true)){ ViewCompat.postInvalidateOnAnimation(this); } }
 
這裏咱們用continueSetting來判斷動畫是否應該繼續,爲何用它呢,api文檔裏提示了:


前面說過每次重繪都會調用computeScroll,而這個方法是空實現,因此咱們就在它裏面判斷是否要繼續執行動畫,返回值爲ture就是繼續執行動畫,固然了,continueSetting()這個方法爲何傳true,
由於這個方法前頭有一段感人肺腑的話:Set this to true if you are calling this method from{@link android.view.View#computeScroll()},讓我節約了很多腦細胞。還有一點,若是繼續執行動畫,
ViewCompat.postInvalidateOnAnimation(this)換成invalidate也能夠。最後是完整代碼,真的沒有150行!!!
public class SwipeLayout extends LinearLayout { private ViewDragHelper helper; public SwipeLayout(Context context) { this(context,null); } public SwipeLayout(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public SwipeLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); helper = ViewDragHelper.create(this,callback); } private ViewDragHelper.Callback callback = new ViewDragHelper.Callback() { private State state; @Override public boolean tryCaptureView(@NonNull View child, int pointerId) { if (getSurfaceView().getLeft() == 0){ state = State.CLOSE; }else { state = State.OPEN; } return true; } @Override public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) { if (child == getSurfaceView()) { if (left > 0) { left = 0; } if (left < -getBottomView().getMeasuredWidth()) { left = -getBottomView().getMeasuredWidth(); } } else { int marleft = getSurfaceView().getMeasuredWidth() - getBottomView().getMeasuredWidth(); if (left < marleft){ left = marleft; } } return left; } @Override public void onViewPositionChanged(@NonNull View changedView, int left, int top, int dx, int dy) { if (changedView == getSurfaceView()){ getBottomView().offsetLeftAndRight(dx); }else { getSurfaceView().offsetLeftAndRight(dx); } invalidate(); } @Override public void onViewReleased(@NonNull View releasedChild, float xvel, float yvel) { float minV = helper.getMinVelocity()*5; float fraction = state == State.CLOSE ? 0.25f:0.75f; if (Math.abs(xvel) > minV){ if (state == State.CLOSE){ if (xvel > 0 ){ close(); }else { open(); } }else { if (xvel >0){ close(); }else { open(); } } }else { //勻速
                if(Math.abs(getSurfaceView().getLeft()) > getBottomView().getMeasuredWidth()*fraction){ open(); }else { close(); } } invalidate(); } }; private void close(){ helper.smoothSlideViewTo(getSurfaceView(), 0, 0); } private void open(){ helper.smoothSlideViewTo(getSurfaceView(),-getBottomView().getMeasuredWidth(),0); } @Override public void computeScroll() { if (helper.continueSettling(true)){ ViewCompat.postInvalidateOnAnimation(this); } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return helper.shouldInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent event) { helper.processTouchEvent(event); return true; } private View getSurfaceView(){ return getChildAt(0); } private View getBottomView(){ return getChildAt(1); } private enum State{ CLOSE, OPEN } }
  至此,這個控件滑一滑是沒問題的,但點一點是沒什麼反應的,下一篇,咱們給這個控件加上點擊事件,仍是基於這個類。相信,基於這個簡單控件的使用,dragViewHelper的基本使用是沒太大問題的。
相關文章
相關標籤/搜索