一、概述
在寫代碼之前,我必須得問幾個問題:
1、ViewGroup的職責是啥?
ViewGroup相當于一個放置View的容器,并且我們在寫布局xml的時候,會告訴容器(凡是以layout為開頭的屬性,都是為用于告訴容器的),我們的寬度(layout_width)、高度(layout_height)、對齊方式(layout_gravity)等;當然還有margin等;于是乎,ViewGroup的職能為:給childView計算出建議的寬和高和測量模式 ;決定childView的位置;為什么只是建議的寬和高,而不是直接確定呢,別忘了childView寬和高可以設置為wrap_content,這樣只有childView才能計算出自己的寬和高。
2、View的職責是啥?
View的職責,根據測量模式和ViewGroup給出的建議的寬和高,計算出自己的寬和高;同時還有個更重要的職責是:在ViewGroup為其指定的區域內繪制自己的形態。
3、ViewGroup和LayoutParams之間的關系?
大家可以回憶一下,當在LinearLayout中寫childView的時候,可以寫layout_gravity,layout_weight屬性;在RelativeLayout中的childView有layout_centerInParent屬性,卻沒有layout_gravity,layout_weight,這是為什么呢?這是因為每個ViewGroup需要指定一個LayoutParams,用于確定支持childView支持哪些屬性,比如LinearLayout指定LinearLayout.LayoutParams等。如果大家去看LinearLayout的源碼,會發現其內部定義了LinearLayout.LayoutParams,在此類中,你可以發現weight和gravity的身影。
二、View的3種測量模式
上面提到了ViewGroup會為childView指定測量模式,下面簡單介紹下三種測量模式:
EXACTLY:表示設置了精確的值,一般當childView設置其寬、高為精確值、match_parent時,ViewGroup會將其設置為EXACTLY;
AT_MOST:表示子布局被限制在一個最大值內,一般當childView設置其寬、高為wrap_content時,ViewGroup會將其設置為AT_MOST;
UNSPECIFIED:表示子布局想要多大就多大,一般出現在AadapterView的item的heightMode中、ScrollView的childView的heightMode中;此種模式比較少見。
注:上面的每一行都有一個一般,意思上述不是絕對的,對于childView的mode的設置還會和ViewGroup的測量mode有一定的關系;當然了,這是第一篇自定義ViewGroup,而且絕大部分情況都是上面的規則,所以為了通俗易懂,暫不深入討論其他內容。
三、從API角度進行淺析
上面敘述了ViewGroup和View的職責,下面從API角度進行淺析。
View的根據ViewGroup傳人的測量值和模式,對自己寬高進行確定(onMeasure中完成),然后在onDraw中完成對自己的繪制。
ViewGroup需要給View傳入view的測量值和模式(onMeasure中完成),而且對于此ViewGroup的父布局,自己也需要在onMeasure中完成對自己寬和高的確定。此外,需要在onLayout中完成對其childView的位置的指定。
四、完整的例子
需求:我們定義一個ViewGroup,內部可以傳入0到4個childView,分別依次顯示在左上角,右上角,左下角,右下角。
1、決定該ViewGroup的LayoutParams
對于我們這個例子,我們只需要ViewGroup能夠支持margin即可,那么我們直接使用系統的MarginLayoutParams
@Override  public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)  {   return new MarginLayoutParams(getContext(), attrs);  } 重寫父類的該方法,返回MarginLayoutParams的實例,這樣就為我們的ViewGroup指定了其LayoutParams為MarginLayoutParams。
2、onMeasure
在onMeasure中計算childView的測量值以及模式,以及設置自己的寬和高:
/**   * 計算所有ChildView的寬度和高度 然后根據ChildView的計算結果,設置自己的寬和高   */  @Override  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  {   /**    * 獲得此ViewGroup上級容器為其推薦的寬和高,以及計算模式    */   int widthMode = MeasureSpec.getMode(widthMeasureSpec);   int heightMode = MeasureSpec.getMode(heightMeasureSpec);   int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);   int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);     // 計算出所有的childView的寬和高   measureChildren(widthMeasureSpec, heightMeasureSpec);   /**    * 記錄如果是wrap_content是設置的寬和高    */   int width = 0;   int height = 0;    int cCount = getChildCount();    int cWidth = 0;   int cHeight = 0;   MarginLayoutParams cParams = null;    // 用于計算左邊兩個childView的高度   int lHeight = 0;   // 用于計算右邊兩個childView的高度,最終高度取二者之間大值   int rHeight = 0;    // 用于計算上邊兩個childView的寬度   int tWidth = 0;   // 用于計算下面兩個childiew的寬度,最終寬度取二者之間大值   int bWidth = 0;    /**    * 根據childView計算的出的寬和高,以及設置的margin計算容器的寬和高,主要用于容器是warp_content時    */   for (int i = 0; i < cCount; i++)   {    View childView = getChildAt(i);    cWidth = childView.getMeasuredWidth();    cHeight = childView.getMeasuredHeight();    cParams = (MarginLayoutParams) childView.getLayoutParams();     // 上面兩個childView    if (i == 0 || i == 1)    {     tWidth += cWidth + cParams.leftMargin + cParams.rightMargin;    }     if (i == 2 || i == 3)    {     bWidth += cWidth + cParams.leftMargin + cParams.rightMargin;    }     if (i == 0 || i == 2)    {     lHeight += cHeight + cParams.topMargin + cParams.bottomMargin;    }     if (i == 1 || i == 3)    {     rHeight += cHeight + cParams.topMargin + cParams.bottomMargin;    }    }      width = Math.max(tWidth, bWidth);   height = Math.max(lHeight, rHeight);    /**    * 如果是wrap_content設置為我們計算的值    * 否則:直接設置為父容器計算的值    */   setMeasuredDimension((widthMode == MeasureSpec.EXACTLY) ? sizeWidth     : width, (heightMode == MeasureSpec.EXACTLY) ? sizeHeight     : height);  } 10-14行,獲取該ViewGroup父容器為其設置的計算模式和尺寸,大多情況下,只要不是wrap_content,父容器都能正確的計算其尺寸。所以我們自己需要計算如果設置為wrap_content時的寬和高,如何計算呢?那就是通過其childView的寬和高來進行計算。
17行,通過ViewGroup的measureChildren方法為其所有的孩子設置寬和高,此行執行完成后,childView的寬和高都已經正確的計算過了
43-71行,根據childView的寬和高,以及margin,計算ViewGroup在wrap_content時的寬和高。
80-82行,如果寬高屬性值為wrap_content,則設置為43-71行中計算的值,否則為其父容器傳入的寬和高。
3、onLayout對其所有childView進行定位(設置childView的繪制區域)
 
// abstract method in viewgroup  @Override  protected void onLayout(boolean changed, int l, int t, int r, int b)  {   int cCount = getChildCount();   int cWidth = 0;   int cHeight = 0;   MarginLayoutParams cParams = null;   /**    * 遍歷所有childView根據其寬和高,以及margin進行布局    */   for (int i = 0; i < cCount; i++)   {    View childView = getChildAt(i);    cWidth = childView.getMeasuredWidth();    cHeight = childView.getMeasuredHeight();    cParams = (MarginLayoutParams) childView.getLayoutParams();     int cl = 0, ct = 0, cr = 0, cb = 0;     switch (i)    {    case 0:     cl = cParams.leftMargin;     ct = cParams.topMargin;     break;    case 1:     cl = getWidth() - cWidth - cParams.leftMargin       - cParams.rightMargin;     ct = cParams.topMargin;      break;    case 2:     cl = cParams.leftMargin;     ct = getHeight() - cHeight - cParams.bottomMargin;     break;    case 3:     cl = getWidth() - cWidth - cParams.leftMargin       - cParams.rightMargin;     ct = getHeight() - cHeight - cParams.bottomMargin;     break;     }    cr = cl + cWidth;    cb = cHeight + ct;    childView.layout(cl, ct, cr, cb);   }   } 代碼比較容易懂:遍歷所有的childView,根據childView的寬和高以及margin,然后分別將0,1,2,3位置的childView依次設置到左上、右上、左下、右下的位置。
如果是第一個View(index=0) :則childView.layout(cl, ct, cr, cb); cl為childView的leftMargin , ct 為topMargin , cr 為cl+ cWidth , cb為 ct + cHeight
如果是第二個View(index=1) :則childView.layout(cl, ct, cr, cb); 
cl為getWidth() - cWidth - cParams.leftMargin- cParams.rightMargin;
ct 為topMargin , cr 為cl+ cWidth , cb為 ct + cHeight
剩下兩個類似~
這樣就完成了,我們的ViewGroup代碼的編寫,下面我們進行測試,分別設置寬高為固定值,wrap_content,match_parent
4、測試結果
布局1:
<com.example.zhy_custom_viewgroup.CustomImgContainer xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="200dp" android:layout_height="200dp" android:background="#AA333333" > <TextView android:layout_width="50dp" android:layout_height="50dp" android:background="#FF4444" android:gravity="center" android:text="0" android:textColor="#FFFFFF" android:textSize="22sp" android:textStyle="bold" /> <TextView android:layout_width="50dp" android:layout_height="50dp" android:background="#00ff00" android:gravity="center" android:text="1" android:textColor="#FFFFFF" android:textSize="22sp" android:textStyle="bold" /> <TextView android:layout_width="50dp" android:layout_height="50dp" android:background="#ff0000" android:gravity="center" android:text="2" android:textColor="#FFFFFF" android:textSize="22sp" android:textStyle="bold" /> <TextView android:layout_width="50dp" android:layout_height="50dp" android:background="#0000ff" android:gravity="center" android:text="3" android:textColor="#FFFFFF" android:textSize="22sp" android:textStyle="bold" /> </com.example.zhy_custom_viewgroup.CustomImgContainer>
ViewGroup寬和高設置為固定值
效果圖:

布局2:
<com.example.zhy_custom_viewgroup.CustomImgContainer xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#AA333333" > <TextView android:layout_width="150dp" android:layout_height="150dp" android:background="#E5ED05" android:gravity="center" android:text="0" android:textColor="#FFFFFF" android:textSize="22sp" android:textStyle="bold" /> <TextView android:layout_width="50dp" android:layout_height="50dp" android:background="#00ff00" android:gravity="center" android:text="1" android:textColor="#FFFFFF" android:textSize="22sp" android:textStyle="bold" /> <TextView android:layout_width="50dp" android:layout_height="50dp" android:background="#ff0000" android:gravity="center" android:text="2" android:textColor="#FFFFFF" android:textSize="22sp" android:textStyle="bold" /> <TextView android:layout_width="50dp" android:layout_height="50dp" android:background="#0000ff" android:gravity="center" android:text="3" android:textColor="#FFFFFF" android:textSize="22sp" android:textStyle="bold" /> </com.example.zhy_custom_viewgroup.CustomImgContainer>
 ViewGroup的寬和高設置為wrap_content
效果圖:

布局3:
<com.example.zhy_custom_viewgroup.CustomImgContainer xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#AA333333" > <TextView android:layout_width="150dp" android:layout_height="150dp" android:background="#E5ED05" android:gravity="center" android:text="0" android:textColor="#FFFFFF" android:textSize="22sp" android:textStyle="bold" /> <TextView android:layout_width="50dp" android:layout_height="50dp" android:background="#00ff00" android:gravity="center" android:text="1" android:textColor="#FFFFFF" android:textSize="22sp" android:textStyle="bold" /> <TextView android:layout_width="50dp" android:layout_height="50dp" android:background="#ff0000" android:gravity="center" android:text="2" android:textColor="#FFFFFF" android:textSize="22sp" android:textStyle="bold" /> <TextView android:layout_width="150dp" android:layout_height="150dp" android:background="#0000ff" android:gravity="center" android:text="3" android:textColor="#FFFFFF" android:textSize="22sp" android:textStyle="bold" /> </com.example.zhy_custom_viewgroup.CustomImgContainer>
ViewGroup的寬和高設置為match_parent

可以看到無論ViewGroup的寬和高的值如何定義,我們的需求都實現了預期的效果~~
四、使用ViewDragHelper自定義ViewGroup
1、概述
在自定義ViewGroup中,很多效果都包含用戶手指去拖動其內部的某個View(eg:側滑菜單等),針對具體的需要去寫好onInterceptTouchEvent和onTouchEvent這兩個方法是一件很不容易的事,需要自己去處理:多手指的處理、加速度檢測等等。 
好在官方在v4的支持包中提供了ViewDragHelper這樣一個類來幫助我們方便的編寫自定義ViewGroup。簡單看一下它的注釋:
ViewDragHelper is a utility class for writing custom ViewGroups. It offers a number 
of useful operations and state tracking for allowing a user to drag and reposition 
views within their parent ViewGroup.
下面將重點介紹ViewDragHelper的使用,并且最終去實現一個類似DrawerLayout的一個自定義的ViewGroup。(ps:官方的DrawerLayout就是用此類實現)
2、入門小示例
首先我們通過一個簡單的例子來看看其快捷的用法,分為以下幾個步驟:
A、創建實例
B、觸摸相關的方法的調用
C、ViewDragHelper.Callback實例的編寫
(1) 自定義ViewGroup
package com.zhy.learn.view;import android.content.Context;import android.support.v4.widget.ViewDragHelper;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;import android.widget.LinearLayout;/** * Created by zhy on 15/6/3. */public class VDHLayout extends LinearLayout{ private ViewDragHelper mDragger; public VDHLayout(Context context, AttributeSet attrs) {  super(context, attrs);  mDragger = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback()  {   @Override   public boolean tryCaptureView(View child, int pointerId)   {    return true;   }   @Override   public int clampViewPositionHorizontal(View child, int left, int dx)   {    return left;   }   @Override   public int clampViewPositionVertical(View child, int top, int dy)   {    return top;   }  }); } @Override public boolean onInterceptTouchEvent(MotionEvent event) {  return mDragger.shouldInterceptTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) {  mDragger.processTouchEvent(event);  return true; }}可以看到,上面整個自定義ViewGroup的代碼非常簡潔,遵循上述3個步驟:
A、創建實例
mDragger = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback()  {  });創建實例需要3個參數,第一個就是當前的ViewGroup,第二個sensitivity,主要用于設置touchSlop:
helper.mTouchSlop = (int) (helper.mTouchSlop * (1 / sensitivity));
可見傳入越大,mTouchSlop的值就會越小。第三個參數就是Callback,在用戶的觸摸過程中會回調相關方法,后面會細說。
B、觸摸相關方法
 @Override public boolean onInterceptTouchEvent(MotionEvent event) {  return mDragger.shouldInterceptTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) {  mDragger.processTouchEvent(event);  return true; }onInterceptTouchEvent中通過使用mDragger.shouldInterceptTouchEvent(event)來決定我們是否應該攔截當前的事件。onTouchEvent中通過mDragger.processTouchEvent(event)處理事件。
C、實現ViewDragHelper.CallCack相關方法
new ViewDragHelper.Callback()  {   @Override   public boolean tryCaptureView(View child, int pointerId)   {    return true;   }   @Override   public int clampViewPositionHorizontal(View child, int left, int dx)   {    return left;   }   @Override   public int clampViewPositionVertical(View child, int top, int dy)   {    return top;   }  }ViewDragHelper中攔截和處理事件時,需要會回調CallBack中的很多方法來決定一些事,比如:哪些子View可以移動、對個移動的View的邊界的控制等等。
上面復寫的3個方法:
tryCaptureView如何返回ture則表示可以捕獲該view,你可以根據傳入的第一個view參數決定哪些可以捕獲
clampViewPositionHorizontal,clampViewPositionVertical可以在該方法中對child移動的邊界進行控制,left , top 分別為即將移動到的位置,比如橫向的情況下,我希望只在ViewGroup的內部移動,即:最小>=paddingleft,最大<=ViewGroup.getWidth()-paddingright-child.getWidth。就可以按照如下代碼編寫:
 @Override   public int clampViewPositionHorizontal(View child, int left, int dx)   {    final int leftBound = getPaddingLeft();    final int rightBound = getWidth() - mDragView.getWidth() - leftBound;    final int newLeft = Math.min(Math.max(left, leftBound), rightBound);    return newLeft;   }經過上述3個步驟,我們就完成了一個簡單的自定義ViewGroup,可以自由的拖動子View。
簡單看一下布局文件
(2) 布局文件
<com.zhy.learn.view.VDHLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" > <TextView android:layout_margin="10dp" android:gravity="center" android:layout_gravity="center" android:background="#44ff0000" android:text="I can be dragged !" android:layout_width="100dp" android:layout_height="100dp"/> <TextView android:layout_margin="10dp" android:layout_gravity="center" android:gravity="center" android:background="#44ff0000" android:text="I can be dragged !" android:layout_width="100dp" android:layout_height="100dp"/> <TextView android:layout_margin="10dp" android:layout_gravity="center" android:gravity="center" android:background="#44ff0000" android:text="I can be dragged !" android:layout_width="100dp" android:layout_height="100dp"/></com.zhy.learn.view.VDHLayout>
我們的自定義ViewGroup中有三個TextView。
當前效果:

可以看到短短數行代碼就可以玩起來了~~~
有了直觀的認識以后,我們還需要對ViewDragHelper.CallBack里面的方法做下深入的理解。首先我們需要考慮的是:我們的ViewDragHelper不僅僅說只能夠去讓子View去跟隨我們手指移動,我們繼續往下學習其他的功能。
3、功能展示
ViewDragHelper還能做以下的一些操作:
邊界檢測、加速度檢測(eg:DrawerLayout邊界觸發拉出)
回調Drag Release(eg:DrawerLayout部分,手指抬起,自動展開/收縮)
移動到某個指定的位置(eg:點擊Button,展開/關閉Drawerlayout)
那么我們接下來對我們最基本的例子進行改造,包含上述的幾個操作。
首先看一下我們修改后的效果:

簡單的為每個子View添加了不同的操作:
第一個View,就是演示簡單的移動 
第二個View,演示除了移動后,松手自動返回到原本的位置。(注意你拖動的越快,返回的越快) 
第三個View,邊界移動時對View進行捕獲。
好了,看完效果圖,來看下代碼的修改:
修改后的代碼
package com.zhy.learn.view;import android.content.Context;import android.graphics.Point;import android.support.v4.widget.ViewDragHelper;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;import android.widget.LinearLayout;/** * Created by zhy on 15/6/3. */public class VDHLayout extends LinearLayout{ private ViewDragHelper mDragger; private View mDragView; private View mAutoBackView; private View mEdgeTrackerView; private Point mAutoBackOriginPos = new Point(); public VDHLayout(Context context, AttributeSet attrs) {  super(context, attrs);  mDragger = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback()  {   @Override   public boolean tryCaptureView(View child, int pointerId)   {    //mEdgeTrackerView禁止直接移動    return child == mDragView || child == mAutoBackView;   }   @Override   public int clampViewPositionHorizontal(View child, int left, int dx)   {    return left;   }   @Override   public int clampViewPositionVertical(View child, int top, int dy)   {    return top;   }   //手指釋放的時候回調   @Override   public void onViewReleased(View releasedChild, float xvel, float yvel)   {    //mAutoBackView手指釋放時可以自動回去    if (releasedChild == mAutoBackView)    {     mDragger.settleCapturedViewAt(mAutoBackOriginPos.x, mAutoBackOriginPos.y);     invalidate();    }   }   //在邊界拖動時回調   @Override   public void onEdgeDragStarted(int edgeFlags, int pointerId)   {    mDragger.captureChildView(mEdgeTrackerView, pointerId);   }  });  mDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT); } @Override public boolean onInterceptTouchEvent(MotionEvent event) {  return mDragger.shouldInterceptTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) {  mDragger.processTouchEvent(event);  return true; } @Override public void computeScroll() {  if(mDragger.continueSettling(true))  {   invalidate();  } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) {  super.onLayout(changed, l, t, r, b);  mAutoBackOriginPos.x = mAutoBackView.getLeft();  mAutoBackOriginPos.y = mAutoBackView.getTop(); } @Override protected void onFinishInflate() {  super.onFinishInflate();  mDragView = getChildAt(0);  mAutoBackView = getChildAt(1);  mEdgeTrackerView = getChildAt(2); }}布局文件我們僅僅是換了下文本和背景色就不重復貼了。
第一個View基本沒做任何修改。
第二個View,我們在onLayout之后保存了最開啟的位置信息,最主要還是重寫了Callback中的onViewReleased,我們在onViewReleased中判斷如果是mAutoBackView則調用settleCapturedViewAt回到初始的位置。大家可以看到緊隨其后的代碼是invalidate();因為其內部使用的是mScroller.startScroll,所以別忘了需要invalidate()以及結合computeScroll方法一起。
第三個View,我們在onEdgeDragStarted回調方法中,主動通過captureChildView對其進行捕獲,該方法可以繞過tryCaptureView,所以我們的tryCaptureView雖然并為返回true,但卻不影響。注意如果需要使用邊界檢測需要添加上mDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT);。
到此,我們已經介紹了Callback中常用的回調方法了,當然還有一些方法沒有介紹,接下來我們修改下我們的布局文件,我們把我們的TextView全部加上clickable=true,意思就是子View可以消耗事件。再次運行,你會發現本來可以拖動的View不動了,(如果有拿Button測試的兄弟應該已經發現這個問題了,我希望你看到這了,而不是已經提問了,哈~)。
原因是什么呢?主要是因為,如果子View不消耗事件,那么整個手勢(DOWN-MOVE*-UP)都是直接進入onTouchEvent,在onTouchEvent的DOWN的時候就確定了captureView。如果消耗事件,那么就會先走onInterceptTouchEvent方法,判斷是否可以捕獲,而在判斷的過程中會去判斷另外兩個回調的方法:getViewHorizontalDragRange和getViewVerticalDragRange,只有這兩個方法返回大于0的值才能正常的捕獲。
所以,如果你用Button測試,或者給TextView添加了clickable = true ,都記得重寫下面這兩個方法:
@Overridepublic int getViewHorizontalDragRange(View child){  return getMeasuredWidth()-child.getMeasuredWidth();}@Overridepublic int getViewVerticalDragRange(View child){  return getMeasuredHeight()-child.getMeasuredHeight();}方法的返回值應當是該childView橫向或者縱向的移動的范圍,當前如果只需要一個方向移動,可以只復寫一個。
到此,我們列一下所有的Callback方法,看看還有哪些沒用過的:
onViewDragStateChanged
當ViewDragHelper狀態發生變化時回調(IDLE,DRAGGING,SETTING[自動滾動時]):
onViewPositionChanged
當captureview的位置發生改變時回調:
onViewCaptured
當captureview被捕獲時回調:
onViewReleased 已用
onEdgeTouched
當觸摸到邊界時回調:
onEdgeLock
true的時候會鎖住當前的邊界,false則unLock。
onEdgeDragStarted 已用
getOrderedChildIndex
改變同一個坐標(x,y)去尋找captureView位置的方法。(具體在:findTopChildUnder方法中)
getViewHorizontalDragRange 已用
getViewVerticalDragRange 已用
tryCaptureView 已用
clampViewPositionHorizontal 已用
clampViewPositionVertical 已用
ok,至此所有的回調方法都有了一定的認識。
總結下,方法的大致的回調順序:
shouldInterceptTouchEvent:DOWN: getOrderedChildIndex(findTopChildUnder) ->onEdgeTouchedMOVE: getOrderedChildIndex(findTopChildUnder) ->getViewHorizontalDragRange & getViewVerticalDragRange(checkTouchSlop)(MOVE中可能不止一次) ->clampViewPositionHorizontal& clampViewPositionVertical ->onEdgeDragStarted ->tryCaptureView ->onViewCaptured ->onViewDragStateChangedprocessTouchEvent:DOWN: getOrderedChildIndex(findTopChildUnder) ->tryCaptureView ->onViewCaptured ->onViewDragStateChanged ->onEdgeTouchedMOVE: ->STATE==DRAGGING:dragTo ->STATE!=DRAGGING: onEdgeDragStarted ->getOrderedChildIndex(findTopChildUnder) ->getViewHorizontalDragRange& getViewVerticalDragRange(checkTouchSlop) ->tryCaptureView ->onViewCaptured ->onViewDragStateChanged
ok,上述是正常情況下大致的流程,當然整個過程可能會存在很多判斷不成立的情況。
從上面也可以解釋,我們在之前TextView(clickable=false)的情況下,沒有編寫getViewHorizontalDragRange方法時,是可以移動的。因為直接進入processTouchEvent的DOWN,然后就onViewCaptured、onViewDragStateChanged(進入DRAGGING狀態),接下來MOVE就直接dragTo了。
而當子View消耗事件的時候,就需要走shouldInterceptTouchEvent,MOVE的時候經過一系列的判斷(getViewHorizontalDragRange,clampViewPositionVertical等),才能夠去tryCaptureView。
ok,到此ViewDragHelper的入門用法我們就介紹結束了,下一篇,我們將使用ViewDragHelper去自己實現一個DrawerLayout。 
有興趣的也可以根據本文,以及DrawerLayout的源碼去實現了~
新聞熱點
疑難解答