国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android應用開發中自定義ViewGroup的究極攻略

2019-12-12 06:22:54
字體:
來源:轉載
供稿:網友

支持margin,gravity以及水平,垂直排列
最近在學習android的view部分,于是動手實現了一個類似ViewPager的可上下或者左右拖動的ViewGroup,中間遇到了一些問題(例如touchEvent在onInterceptTouchEvent和onTouchEvent之間的傳遞流程),現在將我的實現過程記錄下來。

首先,要實現一個ViewGroup,必須至少重寫onLayout()方法(當然還有構造方法啦:))。onLayout()主要是用來安排子View在我們這個ViewGroup中的擺放位置的。除了onLayout()方法之外往往還需要重寫onMeasure()方法,用于測算我們所需要占用的空間。

首先,我們來重寫onMeasure()方法:(先只考慮水平方向)

@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 計算所有child view 要占用的空間 desireWidth = 0; desireHeight = 0; int count = getChildCount(); for (int i = 0; i < count; ++i) {  View v = getChildAt(i);  if (v.getVisibility() != View.GONE) {   measureChild(v, widthMeasureSpec,     heightMeasureSpec);   desireWidth += v.getMeasuredWidth();   desireHeight = Math     .max(desireHeight, v.getMeasuredHeight());  } } // count with padding desireWidth += getPaddingLeft() + getPaddingRight(); desireHeight += getPaddingTop() + getPaddingBottom(); // see if the size is big enough desireWidth = Math.max(desireWidth, getSuggestedMinimumWidth()); desireHeight = Math.max(desireHeight, getSuggestedMinimumHeight()); setMeasuredDimension(resolveSize(desireWidth, widthMeasureSpec),   resolveSize(desireHeight, heightMeasureSpec));}


我們計算出所有Visilibity不是Gone的View的寬度的總和作為viewgroup的最大寬度,以及這些view中的最高的一個作為viewgroup的高度。這里需要注意的是要考慮咱們viewgroup自己的padding。(目前先忽略子View的margin)。
onLayout():

@Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) { final int parentLeft = getPaddingLeft(); final int parentRight = r - l - getPaddingRight(); final int parentTop = getPaddingTop(); final int parentBottom = b - t - getPaddingBottom(); if (BuildConfig.DEBUG)  Log.d("onlayout", "parentleft: " + parentLeft + " parenttop: "    + parentTop + " parentright: " + parentRight    + " parentbottom: " + parentBottom); int left = parentLeft; int top = parentTop; int count = getChildCount(); for (int i = 0; i < count; ++i) {  View v = getChildAt(i);  if (v.getVisibility() != View.GONE) {   final int childWidth = v.getMeasuredWidth();   final int childHeight = v.getMeasuredHeight();    v.layout(left, top, left + childWidth, top + childHeight);    left += childWidth;  } }}


上面的layout方法寫的比較簡單,就是簡單的計算出每個子View的left值,然后調用view的layout方法即可。
現在我們加上xml布局文件,來看一下效果:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.example.testslidelistview.SlideGroup  android:id="@+id/sl"  android:layout_width="match_parent"  android:layout_height="500dp"  android:layout_marginTop="50dp"  android:background="#FFFF00" >  <ImageView   android:id="@+id/iv1"   android:layout_width="150dp"   android:layout_height="300dp"   android:scaleType="fitXY"   android:src="@drawable/lead_page_1" />  <ImageView   android:layout_width="150dp"   android:layout_height="300dp"   android:scaleType="fitXY"   android:src="@drawable/lead_page_2" />  <ImageView   android:layout_width="150dp"   android:layout_height="300dp"   android:scaleType="fitXY"   android:src="@drawable/lead_page_3" /> </com.example.testslidelistview.SlideGroup></LinearLayout>


效果圖如下:

2016520144858588.jpg (270×480)

從效果圖中我們看到,3個小圖連在一起(因為現在不支持margin),然后我們也沒辦法讓他們垂直居中(因為現在還不支持gravity)。

現在我們首先為咱們的ViewGroup增加一個支持margin和gravity的LayoutParams。

@Override protected android.view.ViewGroup.LayoutParams generateDefaultLayoutParams() {  return new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,    ViewGroup.LayoutParams.MATCH_PARENT); } @Override public android.view.ViewGroup.LayoutParams generateLayoutParams(   AttributeSet attrs) {  return new LayoutParams(getContext(), attrs); } @Override protected android.view.ViewGroup.LayoutParams generateLayoutParams(   android.view.ViewGroup.LayoutParams p) {  return new LayoutParams(p); } public static class LayoutParams extends MarginLayoutParams {  public int gravity = -1;  public LayoutParams(Context c, AttributeSet attrs) {   super(c, attrs);   TypedArray ta = c.obtainStyledAttributes(attrs,     R.styleable.SlideGroup);   gravity = ta.getInt(R.styleable.SlideGroup_layout_gravity, -1);   ta.recycle();  }  public LayoutParams(int width, int height) {   this(width, height, -1);  }  public LayoutParams(int width, int height, int gravity) {   super(width, height);   this.gravity = gravity;  }  public LayoutParams(android.view.ViewGroup.LayoutParams source) {   super(source);  }  public LayoutParams(MarginLayoutParams source) {   super(source);  } }


xml的自定義屬性如下:

<?xml version="1.0" encoding="utf-8"?><resources> <attr name="layout_gravity">  <!-- Push object to the top of its container, not changing its size. -->  <flag name="top" value="0x30" />  <!-- Push object to the bottom of its container, not changing its size. -->  <flag name="bottom" value="0x50" />  <!-- Push object to the left of its container, not changing its size. -->  <flag name="left" value="0x03" />  <!-- Push object to the right of its container, not changing its size. -->  <flag name="right" value="0x05" />  <!-- Place object in the vertical center of its container, not changing its size. -->  <flag name="center_vertical" value="0x10" />  <!-- Place object in the horizontal center of its container, not changing its size. -->  <flag name="center_horizontal" value="0x01" /> </attr>  <declare-styleable name="SlideGroup">  <attr name="layout_gravity" /> </declare-styleable></resources>


現在基本的準備工作差不多了,然后需要修改一下onMeasure()和onLayout()。
onMeasure():(上一個版本,我們在計算最大寬度和高度時忽略了margin)

@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 計算所有child view 要占用的空間 desireWidth = 0; desireHeight = 0; int count = getChildCount(); for (int i = 0; i < count; ++i) {  View v = getChildAt(i);  if (v.getVisibility() != View.GONE) {   LayoutParams lp = (LayoutParams) v.getLayoutParams();   //將measureChild改為measureChildWithMargin   measureChildWithMargins(v, widthMeasureSpec, 0,     heightMeasureSpec, 0);   //這里在計算寬度時加上margin   desireWidth += v.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;   desireHeight = Math     .max(desireHeight, v.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);  } } // count with padding desireWidth += getPaddingLeft() + getPaddingRight(); desireHeight += getPaddingTop() + getPaddingBottom(); // see if the size is big enough desireWidth = Math.max(desireWidth, getSuggestedMinimumWidth()); desireHeight = Math.max(desireHeight, getSuggestedMinimumHeight()); setMeasuredDimension(resolveSize(desireWidth, widthMeasureSpec),   resolveSize(desireHeight, heightMeasureSpec));}


onLayout()(加上margin和gravity)

@Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) { final int parentLeft = getPaddingLeft(); final int parentRight = r - l - getPaddingRight(); final int parentTop = getPaddingTop(); final int parentBottom = b - t - getPaddingBottom(); if (BuildConfig.DEBUG)  Log.d("onlayout", "parentleft: " + parentLeft + " parenttop: "    + parentTop + " parentright: " + parentRight    + " parentbottom: " + parentBottom); int left = parentLeft; int top = parentTop; int count = getChildCount(); for (int i = 0; i < count; ++i) {  View v = getChildAt(i);  if (v.getVisibility() != View.GONE) {   LayoutParams lp = (LayoutParams) v.getLayoutParams();   final int childWidth = v.getMeasuredWidth();   final int childHeight = v.getMeasuredHeight();   final int gravity = lp.gravity;   final int horizontalGravity = gravity     & Gravity.HORIZONTAL_GRAVITY_MASK;   final int verticalGravity = gravity     & Gravity.VERTICAL_GRAVITY_MASK;   left += lp.leftMargin;   top = parentTop + lp.topMargin;   if (gravity != -1) {    switch (verticalGravity) {    case Gravity.TOP:     break;    case Gravity.CENTER_VERTICAL:     top = parentTop       + (parentBottom - parentTop - childHeight)       / 2 + lp.topMargin - lp.bottomMargin;     break;    case Gravity.BOTTOM:     top = parentBottom - childHeight - lp.bottomMargin;     break;    }   }   if (BuildConfig.DEBUG) {    Log.d("onlayout", "child[width: " + childWidth      + ", height: " + childHeight + "]");    Log.d("onlayout", "child[left: " + left + ", top: "      + top + ", right: " + (left + childWidth)      + ", bottom: " + (top + childHeight));   }   v.layout(left, top, left + childWidth, top + childHeight);   left += childWidth + lp.rightMargin;     } }}


現在修改一下xml布局文件,加上例如xmlns:ly="http://schemas.android.com/apk/res-auto",的xml命名空間,來引用我們設置的layout_gravity屬性。(這里的“res-auto”其實還可以使用res/com/example/testslidelistview來代替,但是前一種方法相對簡單,尤其是當你將某個ui組件作為library來使用的時候)
現在的效果圖如下:有了margin,有了gravity。

2016520145018412.jpg (270×480)

其實在這個基礎上,我們可以很容易的添加一個方向屬性,使得它可以通過設置一個xml屬性或者一個java api調用來實現垂直排列。

下面我們增加一個用于表示方向的枚舉類型:

public static enum Orientation {  HORIZONTAL(0), VERTICAL(1);    private int value;  private Orientation(int i) {   value = i;  }  public int value() {   return value;  }  public static Orientation valueOf(int i) {   switch (i) {   case 0:    return HORIZONTAL;   case 1:    return VERTICAL;   default:    throw new RuntimeException("[0->HORIZONTAL, 1->VERTICAL]");   }  } }


然后我們需要改變onMeasure(),來正確的根據方向計算需要的最大寬度和高度。

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  // 計算所有child view 要占用的空間  desireWidth = 0;  desireHeight = 0;  int count = getChildCount();  for (int i = 0; i < count; ++i) {   View v = getChildAt(i);   if (v.getVisibility() != View.GONE) {    LayoutParams lp = (LayoutParams) v.getLayoutParams();    measureChildWithMargins(v, widthMeasureSpec, 0,      heightMeasureSpec, 0);    //只是在這里增加了垂直或者水平方向的判斷    if (orientation == Orientation.HORIZONTAL) {     desireWidth += v.getMeasuredWidth() + lp.leftMargin       + lp.rightMargin;     desireHeight = Math.max(desireHeight, v.getMeasuredHeight()       + lp.topMargin + lp.bottomMargin);    } else {     desireWidth = Math.max(desireWidth, v.getMeasuredWidth()       + lp.leftMargin + lp.rightMargin);     desireHeight += v.getMeasuredHeight() + lp.topMargin       + lp.bottomMargin;    }   }  }  // count with padding  desireWidth += getPaddingLeft() + getPaddingRight();  desireHeight += getPaddingTop() + getPaddingBottom();  // see if the size is big enough  desireWidth = Math.max(desireWidth, getSuggestedMinimumWidth());  desireHeight = Math.max(desireHeight, getSuggestedMinimumHeight());  setMeasuredDimension(resolveSize(desireWidth, widthMeasureSpec),    resolveSize(desireHeight, heightMeasureSpec)); }


onLayout():

@Override protected void onLayout(boolean changed, int l, int t, int r, int b) {  final int parentLeft = getPaddingLeft();  final int parentRight = r - l - getPaddingRight();  final int parentTop = getPaddingTop();  final int parentBottom = b - t - getPaddingBottom();  if (BuildConfig.DEBUG)   Log.d("onlayout", "parentleft: " + parentLeft + " parenttop: "     + parentTop + " parentright: " + parentRight     + " parentbottom: " + parentBottom);  int left = parentLeft;  int top = parentTop;  int count = getChildCount();  for (int i = 0; i < count; ++i) {   View v = getChildAt(i);   if (v.getVisibility() != View.GONE) {    LayoutParams lp = (LayoutParams) v.getLayoutParams();    final int childWidth = v.getMeasuredWidth();    final int childHeight = v.getMeasuredHeight();    final int gravity = lp.gravity;    final int horizontalGravity = gravity      & Gravity.HORIZONTAL_GRAVITY_MASK;    final int verticalGravity = gravity      & Gravity.VERTICAL_GRAVITY_MASK;    if (orientation == Orientation.HORIZONTAL) {     // layout horizontally, and only consider vertical gravity     left += lp.leftMargin;     top = parentTop + lp.topMargin;     if (gravity != -1) {      switch (verticalGravity) {      case Gravity.TOP:       break;      case Gravity.CENTER_VERTICAL:       top = parentTop         + (parentBottom - parentTop - childHeight)         / 2 + lp.topMargin - lp.bottomMargin;       break;      case Gravity.BOTTOM:       top = parentBottom - childHeight - lp.bottomMargin;       break;      }     }     if (BuildConfig.DEBUG) {      Log.d("onlayout", "child[width: " + childWidth        + ", height: " + childHeight + "]");      Log.d("onlayout", "child[left: " + left + ", top: "        + top + ", right: " + (left + childWidth)        + ", bottom: " + (top + childHeight));     }     v.layout(left, top, left + childWidth, top + childHeight);     left += childWidth + lp.rightMargin;    } else {     // layout vertical, and only consider horizontal gravity     left = parentLeft;     top += lp.topMargin;     switch (horizontalGravity) {     case Gravity.LEFT:      break;     case Gravity.CENTER_HORIZONTAL:      left = parentLeft        + (parentRight - parentLeft - childWidth) / 2        + lp.leftMargin - lp.rightMargin;      break;     case Gravity.RIGHT:      left = parentRight - childWidth - lp.rightMargin;      break;     }     v.layout(left, top, left + childWidth, top + childHeight);     top += childHeight + lp.bottomMargin;    }   }  } }


現在我們可以增加一個xml屬性:

<attr name="orientation">   <enum name="horizontal" value="0" />   <enum name="vertical" value="1" /></attr>


現在就可以在布局文件中加入ly:orientation="vertical"來實現垂直排列了(ly是自定義的xml命名空間)
布局文件如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.example.testslidelistview.SlideGroup  xmlns:gs="http://schemas.android.com/apk/res-auto"  android:id="@+id/sl"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_marginTop="50dp"  android:background="#FFFF00" >  <ImageView   android:id="@+id/iv1"   android:layout_width="300dp"   android:layout_height="200dp"   android:layout_marginBottom="20dp"   gs:layout_gravity="left"   android:scaleType="fitXY"   android:src="@drawable/lead_page_1" />  <ImageView   android:layout_width="300dp"   android:layout_height="200dp"   android:layout_marginBottom="20dp"   gs:layout_gravity="center_horizontal"   android:scaleType="fitXY"   android:src="@drawable/lead_page_2" />  <ImageView   android:layout_width="300dp"   android:layout_height="200dp"   android:layout_marginBottom="20dp"   gs:layout_gravity="right"   android:scaleType="fitXY"   android:src="@drawable/lead_page_3" /> </com.example.testslidelistview.SlideGroup></LinearLayout>


現在效果圖如下:

2016520145127069.jpg (270×480)

重寫onTouchEvent()以支持滑動:

要使View滑動,我們可以通過調用scrollTo()和scrollBy()來實現,這里需要注意的是:要使頁面向左移動,需要增加mScrollX(就是向scrollBy傳遞一個正數),同樣的,要使頁面向上移動,需要增加mScrollY。

@Overridepublic boolean onTouchEvent(MotionEvent event) { final int action = event.getAction(); if (BuildConfig.DEBUG)  Log.d("onTouchEvent", "action: " + action); switch (action) { case MotionEvent.ACTION_DOWN:  x = event.getX();  y = event.getY();  break; case MotionEvent.ACTION_MOVE:  float mx = event.getX();  float my = event.getY();  //此處的moveBy是根據水平或是垂直排放的方向,  //來選擇是水平移動還是垂直移動  moveBy((int) (x - mx), (int) (y - my));  x = mx;  y = my;  break;  } return true;}//此處的moveBy是根據水平或是垂直排放的方向,//來選擇是水平移動還是垂直移動public void moveBy(int deltaX, int deltaY) { if (BuildConfig.DEBUG)  Log.d("moveBy", "deltaX: " + deltaX + " deltaY: " + deltaY); if (orientation == Orientation.HORIZONTAL) {  if (Math.abs(deltaX) >= Math.abs(deltaY))   scrollBy(deltaX, 0); } else {  if (Math.abs(deltaY) >= Math.abs(deltaX))   scrollBy(0, deltaY); }}



好,現在我們再運行這段代碼,就會發現View已經可以跟隨手指移動了,但現在的問題是當手指離開屏幕后,View就立即停止滑動了,這樣的體驗就相當不友好,那么我們希望手指離開后,View能夠以一定的阻尼滿滿地減速滑動。

借助Scroller,并且處理ACTION_UP事件

Scroller是一個用于計算位置的工具類,它負責計算下一個位置的坐標(根據時長,最小以最大移動距離,以及阻尼算法(可以使用自定義的Interpolator))。

Scroller有兩種模式:scroll和fling。


scroll用于已知目標位置的情況(例如:Viewpager中向左滑動,就是要展示右邊的一頁,那么我們就可以準確計算出滑動的目標位置,此時就可以使用Scroller.startScroll()方法)
fling用于不能準確得知目標位置的情況(例如:ListView,每一次的滑動,我們事先都不知道滑動距離,而是根據手指抬起是的速度來判斷是滑遠一點還是近一點,這時就可以使用Scroller.fling()方法)
現在我們改一下上面的onTouchEvent()方法,增加對ACTION_UP事件的處理,以及初速度的計算。

@Overridepublic boolean onTouchEvent(MotionEvent event) { final int action = event.getAction(); if (BuildConfig.DEBUG)  Log.d("onTouchEvent", "action: " + action); //將事件加入到VelocityTracker中,用于計算手指抬起時的初速度 if (velocityTracker == null) {  velocityTracker = VelocityTracker.obtain(); } velocityTracker.addMovement(event); switch (action) { case MotionEvent.ACTION_DOWN:  x = event.getX();  y = event.getY();  if (!mScroller.isFinished())   mScroller.abortAnimation();  break; case MotionEvent.ACTION_MOVE:  float mx = event.getX();  float my = event.getY();  moveBy((int) (x - mx), (int) (y - my));  x = mx;  y = my;  break; case MotionEvent.ACTION_UP:  //maxFlingVelocity是通過ViewConfiguration來獲取的初速度的上限  //這個值可能會因為屏幕的不同而不同  velocityTracker.computeCurrentVelocity(1000, maxFlingVelocity);  float velocityX = velocityTracker.getXVelocity();  float velocityY = velocityTracker.getYVelocity();  //用來處理實際的移動  completeMove(-velocityX, -velocityY);  if (velocityTracker != null) {   velocityTracker.recycle();   velocityTracker = null;  }  break; return true;}


我們在computeMove()中調用Scroller的fling()方法,順便考慮一下滑動方向問題

private void completeMove(float velocityX, float velocityY) { if (orientation == Orientation.HORIZONTAL) {  int mScrollX = getScrollX();  int maxX = desireWidth - getWidth();// - Math.abs(mScrollX);  if (Math.abs(velocityX) >= minFlingVelocity && maxX > 0) {      mScroller.fling(mScrollX, 0, (int) velocityX, 0, 0, maxX, 0, 0);   invalidate();  } } else {  int mScrollY = getScrollY();  int maxY = desireHeight - getHeight();// - Math.abs(mScrollY);  if (Math.abs(velocityY) >= minFlingVelocity && maxY > 0) {      mScroller.fling(0, mScrollY, 0, (int) velocityY, 0, 0, 0, maxY);   invalidate();  } }}


好了,現在我們再運行一遍,問題又來了,手指抬起后,頁面立刻又停了下來,并沒有實現慢慢減速的滑動效果。

其實原因就是上面所說的,Scroller只是幫助我們計算位置的,并不處理View的滑動。我們要想實現連續的滑動效果,那就要在View繪制完成后,再通過Scroller獲得新位置,然后再重繪,如此反復,直至停止。

重寫computeScroll(),實現View的連續繪制

@Overridepublic void computeScroll() { if (mScroller.computeScrollOffset()) {  if (orientation == Orientation.HORIZONTAL) {   scrollTo(mScroller.getCurrX(), 0);   postInvalidate();  } else {   scrollTo(0, mScroller.getCurrY());   postInvalidate();  } }}


computeScroll()是在ViewGroup的drawChild()中調用的,上面的代碼中,我們通過調用computeScrollOffset()來判斷滑動是否已停止,如果沒有,那么我們可以通過getCurrX()和getCurrY()來獲得新位置,然后通過調用scrollTo()來實現滑動,這里需要注意的是postInvalidate()的調用,它會將重繪的這個Event加入UI線程的消息隊列,等scrollTo()執行完成后,就會處理這個事件,然后再次調用ViewGroup的draw()-->drawChild()-->computeScroll()-->scrollTo()如此就實現了連續繪制的效果。

現在我們再重新運行一下app,終于可以持續滑動了:),不過,當我們緩慢地拖動View,慢慢抬起手指,我們會發現通過這樣的方式,可以使得所有的子View滑到屏幕之外,(所有的子View都消失了:()。

問題主要是出在completeMove()中,我們只是判斷了初始速度是否大于最小閾值,如果小于這個最小閾值的話就什么都不做,缺少了邊界的判斷,因此修改computeMove()如下:

private void completeMove(float velocityX, float velocityY) { if (orientation == Orientation.HORIZONTAL) {  int mScrollX = getScrollX();  int maxX = desireWidth - getWidth();  if (mScrollX > maxX) {   // 超出了右邊界,彈回   mScroller.startScroll(mScrollX, 0, maxX - mScrollX, 0);   invalidate();  } else if (mScrollX < 0) {   // 超出了左邊界,彈回   mScroller.startScroll(mScrollX, 0, -mScrollX, 0);   invalidate();  } else if (Math.abs(velocityX) >= minFlingVelocity && maxX > 0) {   mScroller.fling(mScrollX, 0, (int) velocityX, 0, 0, maxX, 0, 0);   invalidate();  } } else {  int mScrollY = getScrollY();  int maxY = desireHeight - getHeight();  if (mScrollY > maxY) {   // 超出了下邊界,彈回   mScroller.startScroll(0, mScrollY, 0, maxY - mScrollY);   invalidate();  } else if (mScrollY < 0) {   // 超出了上邊界,彈回   mScroller.startScroll(0, mScrollY, 0, -mScrollY);   invalidate();  } else if (Math.abs(velocityY) >= minFlingVelocity && maxY > 0) {   mScroller.fling(0, mScrollY, 0, (int) velocityY, 0, 0, 0, maxY);   invalidate();  } }}

ok,現在當我們滑出邊界,松手后,會自動彈回。

處理ACTION_POINTER_UP事件,解決多指交替滑動跳動的問題

現在ViewGroup可以靈活的滑動了,但是當我們使用多個指頭交替滑動時,就會產生跳動的現象。原因是這樣的:

我們實現onTouchEvent()的時候,是通過event.getX(),以及event.getY()來獲取觸摸坐標的,實際上是獲取的手指索引為0的位置坐標,當我們放上第二個手指后,這第二個手指的索引為1,此時我們同時滑動這兩個手指,會發現沒有問題,因為我們追蹤的是手指索引為0的手指位置。但是當我們抬起第一個手指后,問題就出現了, 因為這個時候原本索引為1的第二個手指的索引變為了0,所以我們追蹤的軌跡就出現了錯誤。

簡單來說,跳動就是因為追蹤的手指的改變,而這兩個手指之間原本存在間隙,而這個間隙的距離就是我們跳動的距離。

其實問題產生的根本原因就是手指的索引會變化,因此我們需要記錄被追蹤手指的id,然后當有手指離開屏幕時,判斷離開的手指是否是我們正在追蹤的手指:

如果不是,忽略;
如果是,則選擇一個新的手指作為被追蹤手指,并且調整位置記錄。
還有一點就是,要處理ACTION_POINTER_UP事件,就需要給action與上一個掩碼:event.getAction()&MotionEvent.ACTION_MASK 或者使用 event.getActionMasked()方法。

更改后的onTouchEvent()的實現如下:

@Overridepublic boolean onTouchEvent(MotionEvent event) { final int action = event.getActionMasked(); if (velocityTracker == null) {  velocityTracker = VelocityTracker.obtain(); } velocityTracker.addMovement(event); switch (action) { case MotionEvent.ACTION_DOWN:  // 獲取索引為0的手指id  mPointerId = event.getPointerId(0);  x = event.getX();  y = event.getY();  if (!mScroller.isFinished())   mScroller.abortAnimation();  break; case MotionEvent.ACTION_MOVE:  // 獲取當前手指id所對應的索引,雖然在ACTION_DOWN的時候,我們默認選取索引為0  // 的手指,但當有第二個手指觸摸,并且先前有效的手指up之后,我們會調整有效手指  // 屏幕上可能有多個手指,我們需要保證使用的是同一個手指的移動軌跡,  // 因此此處不能使用event.getActionIndex()來獲得索引  final int pointerIndex = event.findPointerIndex(mPointerId);  float mx = event.getX(pointerIndex);  float my = event.getY(pointerIndex);  moveBy((int) (x - mx), (int) (y - my));  x = mx;  y = my;  break; case MotionEvent.ACTION_UP:  velocityTracker.computeCurrentVelocity(1000, maxFlingVelocity);  float velocityX = velocityTracker.getXVelocity(mPointerId);  float velocityY = velocityTracker.getYVelocity(mPointerId);  completeMove(-velocityX, -velocityY);  if (velocityTracker != null) {   velocityTracker.recycle();   velocityTracker = null;  }  break;  case MotionEvent.ACTION_POINTER_UP:  // 獲取離開屏幕的手指的索引  int pointerIndexLeave = event.getActionIndex();  int pointerIdLeave = event.getPointerId(pointerIndexLeave);  if (mPointerId == pointerIdLeave) {   // 離開屏幕的正是目前的有效手指,此處需要重新調整,并且需要重置VelocityTracker   int reIndex = pointerIndexLeave == 0 ? 1 : 0;   mPointerId = event.getPointerId(reIndex);   // 調整觸摸位置,防止出現跳動   x = event.getX(reIndex);   y = event.getY(reIndex);   if (velocityTracker != null)    velocityTracker.clear();  }   break;  } return true;}


好了,現在我們用多個手指交替滑動就很正常了。
我們解決了多個手指交替滑動帶來的頁面的跳動問題。但同時也還遺留了兩個問題。

我們自定義的這個ViewGroup本身還不支持onClick, onLongClick事件。
當我們給子View設置click事件后,我們的ViewGroup居然不能滑動了。
相對來講,第一個問題稍稍容易處理一點,這里我們先說一下第二個問題。

onInterceptTouchEvent()的作用以及何時會被調用

onInterceptTouchEvent()是用來給ViewGroup自己一個攔截事件的機會,當ViewGroup意識到某個Touch事件應該由自己處理,那么就可以通過此方法來阻止事件被分發到子View中。

為什么onInterceptTouchEvent()方法只接收到來ACTION_DOWN事件??需要處理ACTION_MOVE,ACTION_UP等等事件嗎??

按照google官方文檔的說明:

如果onInterceptTouchEvent方法返回true,那么它將不會收到后續事件,事件將會直接傳遞給目標的onTouchEvent方法(其實會先傳給目標的onTouch方法);
如果onInterceptTouchEvent方法返回false,那么所有的后續事件都會先傳給onInterceptTouchEvent,然后再傳給目標的onTouchEvent方法。
但是,為什么我們在onInterceptTouchEvent方法中返回false之后,卻收不到后續的事件呢??通過實驗以及stackoverflow上面的一些問答得知,當我們在onInterceptTouchEvent()方法中返回false,且子View的onTouchEvent返回true的情況下,onInterceptTouchEvent方法才會收到后續的事件。

雖然這個結果與官方文檔的說法有點不同,但實驗說明是正確的。仔細想想這樣的邏輯也確實非常合理:因為onInterceptTouchEvent方法是用來攔截觸摸事件,防止被子View捕獲。那么現在子View在onTouchEvent中返回false,明確聲明自己不會處理這個觸摸事件,那么這個時候還需要攔截嗎?當然就不需要了,因此onInterceptTouchEvent不需要攔截這個事件,那也就沒有必要將后續事件再傳給它了。

還有就是onInterceptTouchEvent()被調用的前提是它的子View沒有調用requestDisallowInterceptTouchEvent(true)方法(這個方法用于阻止ViewGroup攔截事件)。

ViewGroup的onInterceptTouchEvent方法,onTouchEvent方法以及View的onTouchEvent方法之間的事件傳遞流程

畫了一個簡單的圖,如下:

2016520145306416.png (612×539)

其中:Intercept指的是onInterceptTouchEvent()方法,Touch指的是onTouchEvent()方法。

好了,現在我們可以解決博客開頭列出的第二個問題了,之所以為子View設置click之后,我們的ViewGroup方法無法滑動,是因為,子View在接受到ACTION_DOWN事件后返回true,并且ViewGroup的onInterceptTouchEvent()方法的默認實現是返回false(就是完全不攔截),所以后續的ACTION_MOVE,ACTION_UP事件都傳遞給了子View,因此我們的ViewGroup自然就無法滑動了。

解決方法就是重寫onInterceptTouchEvent方法:

/**  * onInterceptTouchEvent()用來詢問是否要攔截處理。 onTouchEvent()是用來進行處理。  *   * 例如:parentLayout----childLayout----childView 事件的分發流程:  * parentLayout::onInterceptTouchEvent()---false?--->  * childLayout::onInterceptTouchEvent()---false?--->  * childView::onTouchEvent()---false?--->  * childLayout::onTouchEvent()---false?---> parentLayout::onTouchEvent()  *   *   *   * 如果onInterceptTouchEvent()返回false,且分發的子View的onTouchEvent()中返回true,  * 那么onInterceptTouchEvent()將收到所有的后續事件。  *   * 如果onInterceptTouchEvent()返回true,原本的target將收到ACTION_CANCEL,該事件  * 將會發送給我們自己的onTouchEvent()。  */ @Override public boolean onInterceptTouchEvent(MotionEvent ev) {  final int action = ev.getActionMasked();  if (BuildConfig.DEBUG)   Log.d("onInterceptTouchEvent", "action: " + action);  if (action == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {   // 該事件可能不是我們的   return false;  }  boolean isIntercept = false;  switch (action) {  case MotionEvent.ACTION_DOWN:   // 如果動畫還未結束,則將此事件交給onTouchEvet()處理,   // 否則,先分發給子View   isIntercept = !mScroller.isFinished();   // 如果此時不攔截ACTION_DOWN時間,應該記錄下觸摸地址及手指id,當我們決定攔截ACTION_MOVE的event時,   // 將會需要這些初始信息(因為我們的onTouchEvent將可能接收不到ACTION_DOWN事件)   mPointerId = ev.getPointerId(0);// if (!isIntercept) {   downX = x = ev.getX();   downY = y = ev.getY();// }   break;  case MotionEvent.ACTION_MOVE:   int pointerIndex = ev.findPointerIndex(mPointerId);   if (BuildConfig.DEBUG)    Log.d("onInterceptTouchEvent", "pointerIndex: " + pointerIndex      + ", pointerId: " + mPointerId);   float mx = ev.getX(pointerIndex);   float my = ev.getY(pointerIndex);   if (BuildConfig.DEBUG)    Log.d("onInterceptTouchEvent", "action_move [touchSlop: "      + mTouchSlop + ", deltaX: " + (x - mx) + ", deltaY: "      + (y - my) + "]");   // 根據方向進行攔截,(其實這樣,如果我們的方向是水平的,里面有一個ScrollView,那么我們是支持嵌套的)   if (orientation == Orientation.HORIZONTAL) {    if (Math.abs(x - mx) >= mTouchSlop) {     // we get a move event for ourself     isIntercept = true;    }   } else {    if (Math.abs(y - my) >= mTouchSlop) {     isIntercept = true;    }   }   //如果不攔截的話,我們不會更新位置,這樣可以通過累積小的移動距離來判斷是否達到可以認為是Move的閾值。   //這里當產生攔截的話,會更新位置(這樣相當于損失了mTouchSlop的移動距離,如果不更新,可能會有一點點跳的感覺)   if (isIntercept) {    x = mx;    y = my;   }   break;  case MotionEvent.ACTION_CANCEL:  case MotionEvent.ACTION_UP:   // 這是觸摸的最后一個事件,無論如何都不會攔截   if (velocityTracker != null) {    velocityTracker.recycle();    velocityTracker = null;   }   break;  case MotionEvent.ACTION_POINTER_UP:   solvePointerUp(ev);   break;  }  return isIntercept; }private void solvePointerUp(MotionEvent event) {  // 獲取離開屏幕的手指的索引  int pointerIndexLeave = event.getActionIndex();  int pointerIdLeave = event.getPointerId(pointerIndexLeave);  if (mPointerId == pointerIdLeave) {   // 離開屏幕的正是目前的有效手指,此處需要重新調整,并且需要重置VelocityTracker   int reIndex = pointerIndexLeave == 0 ? 1 : 0;   mPointerId = event.getPointerId(reIndex);   // 調整觸摸位置,防止出現跳動   x = event.getX(reIndex);   y = event.getY(reIndex);   if (velocityTracker != null)    velocityTracker.clear();  } }


現在再運行app,問題應該解決了。
onTouchEvent收到ACTION_DOWN,是否一定能收到ACTION_MOVE,ACTION_UP...???     收到了ACTION_MOVE,能否說明它已經收到過ACTION_DOWN???

其實根據上面所說的onInterceptTouchEvent方法與onTouchEvent方法之間事件傳遞的過程,我們知道這兩個問題的答案都是否定的。

對于第一個,收到ACTION_DOWN事件后,ACTION_MOVE事件可能會被攔截,那么它將只能夠再收到一個ACTION_CANCEL事件。

對于第二個,是基于上面的這一個情況,ACTION_DOWN傳遞給了子View,而onInterceptTouchEvent攔截了ACTION_MOVE事件,所以我們的onTouchEvent方法將會收到ACTION_MOVE,而不會收到ACTION_DOWN。(這也是為什么我在onInterceptTouchEvent方法的ACTION_DOWN中記錄下位置信息的原因)

還有一個問題就是,如果我們單純的在onTouchEvent中: 對于ACTION_DOWN返回true,在接收到ACTION_MOVE事件后返回false,那么這個時候事件會重新尋找能處理它的View嗎?不會,所有的后續事件依然會發給這個onTouchEvent方法。


讓ViewGroup支持click事件

這里我們是在onTouchEvent中對于ACTION_UP多做了一些處理:

判斷從按下時的位置到現在的移動距離是否小于可被識別為Move的閾值。
根據ACTION_DOWN和ACTION_UP之間的時間差,判斷是CLICK,還是LONG CLICK(這里當沒有設置long click的話,我們也可將其認為是click)

case MotionEvent.ACTION_UP:   //先判斷是否是點擊事件   final int pi = event.findPointerIndex(mPointerId);      if((isClickable() || isLongClickable())      && ((event.getX(pi) - downX) < mTouchSlop || (event.getY(pi) - downY) < mTouchSlop)) {    //這里我們得到了一個點擊事件    if(isFocusable() && isFocusableInTouchMode() && !isFocused())     requestFocus();    if(event.getEventTime() - event.getDownTime() >= ViewConfiguration.getLongPressTimeout() && isLongClickable()) {     //是一個長按事件     performLongClick();    } else {     performClick();    }   } else {    velocityTracker.computeCurrentVelocity(1000, maxFlingVelocity);    float velocityX = velocityTracker.getXVelocity(mPointerId);    float velocityY = velocityTracker.getYVelocity(mPointerId);     completeMove(-velocityX, -velocityY);    if (velocityTracker != null) {     velocityTracker.recycle();     velocityTracker = null;    }   }   break;

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 桂平市| 临湘市| 屏山县| 策勒县| 扶余县| 静海县| 来宾市| 和龙市| 隆化县| 海丰县| 辉县市| 乌兰县| 永胜县| 浦县| 浮山县| 赣榆县| 临西县| 东乡| 建平县| 定日县| 兴和县| 平度市| 西充县| 宜兴市| 雅江县| 永德县| 广元市| 如皋市| 榆社县| 外汇| 盱眙县| 华阴市| 武陟县| 漠河县| 古交市| 濮阳市| 松溪县| 中牟县| 泗水县| 杨浦区| 沁源县|