Android4.0 Launcherソースコード分析シリーズ(三)


この記事では、デスクトップ全体の左右のスライドがどのように実現されているかを研究します.まずバカはまず図を描いてワークスペースの構造を説明します.次の図を示します.
 
onTouchEventメソッド、詳細はコードコメントを参照:
 
最後に小さな知識点を明らかにしなければならないので、多くのネットユーザーが私に聞いたことがあります.つまりscrollToとscrollByの違いです.ビュークラスのソースコードを見ると、mScrolXは現在のビューが画面座標に対して水平方向のオフセット量を記録し、mScrolYは記録時の現在のビューが画面に対して垂直方向のオフセット量を記録している.
以下のコードから分かるように、scrollToはViewを画面のXとY位置、つまり絶対位置に移動することです.一方、scrollByは呼び出しのscrollToであるが、パラメータは現在のmScrollXとmScrollYにXとYを加えた位置であるため、ScrollByはmScrollXとmScrollYに対する位置を呼び出す.上のコードでは、指が移動画面を置かないとscrollByを呼び出して相対的な距離を移動することがわかります.指を離すとmScrollerが呼び出されますstartScroll(mUnboundedScrollX, 0, delta, 0, duration);を使用して、対応するページに移動するアニメーションを生成します.このプロセスで、システムはcomputeScroll()を呼び出し続け、scrollToを使用して、Viewを現在のScrollerが存在する絶対位置に移動します.
 
   
   
   
   
  1. /** 
  2.      * Set the scrolled position of your view. This will cause a call to 
  3.      * {@link #onScrollChanged(int, int, int, int)} and the view will be 
  4.      * invalidated. 
  5.      * @param x the x position to scroll to 
  6.      * @param y the y position to scroll to 
  7.      */ 
  8.     public void scrollTo(int x, int y) { 
  9.         if (mScrollX != x || mScrollY != y) { 
  10.             int oldX = mScrollX; 
  11.             int oldY = mScrollY; 
  12.             mScrollX = x; 
  13.             mScrollY = y; 
  14.             invalidateParentCaches(); 
  15.             onScrollChanged(mScrollX, mScrollY, oldX, oldY); 
  16.             if (!awakenScrollBars()) { 
  17.                 invalidate(true); 
  18.             } 
  19.         } 
  20.     } 
  21.     /** 
  22.      * Move the scrolled position of your view. This will cause a call to 
  23.      * {@link #onScrollChanged(int, int, int, int)} and the view will be 
  24.      * invalidated. 
  25.      * @param x the amount of pixels to scroll by horizontally 
  26.      * @param y the amount of pixels to scroll by vertically 
  27.      */ 
  28.     public void scrollBy(int x, int y) { 
  29.         scrollTo(mScrollX + x, mScrollY + y); 
  30.     } 

 


 
   
   
   
   
  1. @Override 
  2. public boolean onTouchEvent(MotionEvent ev) { 
  3.     // Skip touch handling if there are no pages to swipe 
  4.     //  ,  
  5.     if (getChildCount() <= 0return super.onTouchEvent(ev); 
  6.  
  7.     acquireVelocityTrackerAndAddMovement(ev); 
  8.  
  9.     final int action = ev.getAction(); 
  10.  
  11.     switch (action & MotionEvent.ACTION_MASK) { 
  12.     case MotionEvent.ACTION_DOWN: 
  13.         /* 
  14.          * If being flinged and user touches, stop the fling. isFinished 
  15.          * will be false if being flinged. 
  16.          *  , , 。 
  17.          *  isFinished false. 
  18.          */ 
  19.         if (!mScroller.isFinished()) { 
  20.             mScroller.abortAnimation(); 
  21.         } 
  22.  
  23.         // Remember where the motion event started 
  24.         mDownMotionX = mLastMotionX = ev.getX(); 
  25.         mLastMotionXRemainder = 0
  26.         mTotalMotionX = 0
  27.         mActivePointerId = ev.getPointerId(0); 
  28.         // , , , 。 
  29.         if (mTouchState == TOUCH_STATE_SCROLLING) { 
  30.             pageBeginMoving(); 
  31.         } 
  32.         break
  33.  
  34.     case MotionEvent.ACTION_MOVE: 
  35.         if (mTouchState == TOUCH_STATE_SCROLLING) { 
  36.             // Scroll to follow the motion event 
  37.             final int pointerIndex = ev.findPointerIndex(mActivePointerId); 
  38.             final float x = ev.getX(pointerIndex); 
  39.             final float deltaX = mLastMotionX + mLastMotionXRemainder - x; 
  40.             //  
  41.             mTotalMotionX += Math.abs(deltaX); 
  42.  
  43.             // Only scroll and update mLastMotionX if we have moved some discrete amount.  We 
  44.             // keep the remainder because we are actually testing if we've moved from the last 
  45.             // scrolled position (which is discrete). 
  46.             //  , mLastMotionX 。 Remainder  
  47.             // 。                
  48.             if (Math.abs(deltaX) >= 1.0f) { 
  49.                 mTouchX += deltaX; 
  50.                 mSmoothingTime = System.nanoTime() / NANOTIME_DIV; 
  51.                 if (!mDeferScrollUpdate) { 
  52.                     scrollBy((int) deltaX, 0); 
  53.                     if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX); 
  54.                 } else { 
  55.                     invalidate(); 
  56.                 } 
  57.                 mLastMotionX = x; 
  58.                 mLastMotionXRemainder = deltaX - (int) deltaX; 
  59.             } else { 
  60.             //Trigger the scrollbars to draw. When invoked this method starts an animation to fade the  
  61.             //scrollbars out after a default delay. If a subclass provides animated scrolling,  
  62.             //the start delay should equal the duration of the scrolling animation. 
  63.             // scrollbar 。  scrollbars 。 ,  
  64.             // 。 
  65.                 awakenScrollBars(); 
  66.             } 
  67.         } else { 
  68.             determineScrollingStart(ev); 
  69.         } 
  70.         break
  71.  
  72.     case MotionEvent.ACTION_UP: 
  73.         if (mTouchState == TOUCH_STATE_SCROLLING) { 
  74.             final int activePointerId = mActivePointerId; 
  75.             final int pointerIndex = ev.findPointerIndex(activePointerId); 
  76.             final float x = ev.getX(pointerIndex); 
  77.             final VelocityTracker velocityTracker = mVelocityTracker; 
  78.             velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 
  79.             int velocityX = (int) velocityTracker.getXVelocity(activePointerId); 
  80.             final int deltaX = (int) (x - mDownMotionX); 
  81.             final int pageWidth = getScaledMeasuredWidth(getPageAt(mCurrentPage)); 
  82.             //  *0.4f 
  83.             boolean isSignificantMove = Math.abs(deltaX) > pageWidth * 
  84.                     SIGNIFICANT_MOVE_THRESHOLD; 
  85.             final int snapVelocity = mSnapVelocity; 
  86.  
  87.             mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x); 
  88.  
  89.             boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING && 
  90.                     Math.abs(velocityX) > snapVelocity; 
  91.  
  92.             // In the case that the page is moved far to one direction and then is flung 
  93.             // in the opposite direction, we use a threshold to determine whether we should 
  94.             // just return to the starting page, or if we should skip one further. 
  95.             //  , 。          
  96.             boolean returnToOriginalPage = false
  97.             if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD && 
  98.                     Math.signum(velocityX) != Math.signum(deltaX) && isFling) { 
  99.                 returnToOriginalPage = true
  100.             } 
  101.  
  102.             int finalPage; 
  103.             // We give flings precedence over large moves, which is why we short-circuit our 
  104.             // test for a large move if a fling has been registered. That is, a large 
  105.             // move to the left and fling to the right will register as a fling to the right. 
  106.             //  
  107.             if (((isSignificantMove && deltaX > 0 && !isFling) || 
  108.                     (isFling && velocityX > 0)) && mCurrentPage > 0) { 
  109.                 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1
  110.                 snapToPageWithVelocity(finalPage, velocityX); 
  111.             //  
  112.             } else if (((isSignificantMove && deltaX 0 && !isFling) || 
  113.                     (isFling && velocityX 0)) && 
  114.                     mCurrentPage 1) { 
  115.                 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1
  116.                 snapToPageWithVelocity(finalPage, velocityX); 
  117.             //  
  118.             } else { 
  119.                 snapToDestination(); 
  120.             } 
  121.         } 
  122.          //  
  123.          else if (mTouchState == TOUCH_STATE_PREV_PAGE) { 
  124.             // at this point we have not moved beyond the touch slop 
  125.             // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so 
  126.             // we can just page 
  127.             int nextPage = Math.max(0, mCurrentPage - 1); 
  128.             if (nextPage != mCurrentPage) { 
  129.                 snapToPage(nextPage); 
  130.             } else { 
  131.                 snapToDestination(); 
  132.             } 
  133.         } 
  134.          //  
  135.          else if (mTouchState == TOUCH_STATE_NEXT_PAGE) { 
  136.             // at this point we have not moved beyond the touch slop 
  137.             // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so 
  138.             // we can just page 
  139.             int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1); 
  140.             if (nextPage != mCurrentPage) { 
  141.                 snapToPage(nextPage); 
  142.             } else { 
  143.                 snapToDestination(); 
  144.             } 
  145.         } else { 
  146.             onUnhandledTap(ev); 
  147.         } 
  148.         mTouchState = TOUCH_STATE_REST; 
  149.         mActivePointerId = INVALID_POINTER; 
  150.         releaseVelocityTracker(); 
  151.         break
  152.      //  
  153.     case MotionEvent.ACTION_CANCEL: 
  154.         if (mTouchState == TOUCH_STATE_SCROLLING) { 
  155.             snapToDestination(); 
  156.         } 
  157.         mTouchState = TOUCH_STATE_REST; 
  158.         mActivePointerId = INVALID_POINTER; 
  159.         releaseVelocityTracker(); 
  160.         break
  161.  
  162.     case MotionEvent.ACTION_POINTER_UP: 
  163.         onSecondaryPointerUp(ev); 
  164.         break
  165.     } 
  166.  
  167.     return true

デスクトップの左右スライド機能は主にPagedViewクラスで実現されるが、WorkSpaceはPagedViewクラスのサブクラスであるため、PagedViewでのメソッドを継承する.私たちの指でWorkSpaceをクリックすると、まずPageViewのonInterceptTouchEvent()メソッドがトリガーされ、対応する条件に基づいてTouchイベントがブロックされるかどうかを判断し、onInterceptTouchEvent()メソッドがtrueに戻るとTouchイベントがブロックされ、PageViewクラスのonTouchメソッドが応答して呼び出されます.falseに戻ると、(1)サブコントロールキーをクリックしてスライドする場合、例えばデスクトップのアイコンをクリックして左右にスライドする場合、workspaceはTouchイベントをサブコントロールに配布します.(2)デスクトップの空白をクリックするだけでTouchイベントに応答しない.
私たちの指が初めて画面に触れると、まずonInterceptTouchEventの中のイベントを判断し、イベント(MotionEvent.ACTION_DOWN)を押すと、押した時のX座標、Y座標などのデータが記録されるとともに、現在のWorkspaceの状態をスクロール状態(OUCH_STATE_SCROLLING)に変更し、そのときtureに戻り、イベントをonTouchEvent関数に渡して処理し、onTouchEventでも同様にイベントタイプを判断しており、イベントメソッドが(otionEvent.ACTION_DOWN)の場合、スクロールした指示バーの表示を開始することができます(Hotseatに第数画面が表示されている画面ポイントです).スクリーンを押しながらスライドすると、onInterceptTouchEventでイベントブロックが行われますが、現在のイベントタイプはMotionEventに変わります.ACTION_MOVEは、移動の操作なので、ブロック時にデスクトップ長押しのイベントへの応答をキャンセルするとともに、onTouchEventでACTION_MOVEイベントの応答では,我々がどれだけの距離を移動したかを判断し,scrollBy法を用いてデスクトップを移動し,画面をリフレッシュする.最後に手を離すとonTouchEventのMotionEventがトリガーされます.ACTION_UPイベントでは、スライドの状況に応じて左にスライドするか右にスライドするかを判断し、指が画面幅の半分以下の距離だけスライドすると元のページに戻り、画面幅の半分以上スライドするとページをめくる.また、ワークスペーススライドのイベントがどのような場合にトリガーされても、computeScroll()メソッドが呼び出され続け、このメソッドを書き換えながらインタフェースのリフレッシュなどの操作を呼び出すことに注意してください.
スライド中に注意すべき主な方法は、コードコメントを参照してください.   
 
   
   
   
   
  1. // Touch     Touch , mTouchState  
  2. @Override 
  3. public boolean onInterceptTouchEvent(MotionEvent ev) { 
  4.     /* 
  5.      * This method JUST determines whether we want to intercept the motion. 
  6.      * If we return true, onTouchEvent will be called and we do the actual 
  7.      * scrolling there. 
  8.      *  , true, onTouchEvent  
  9.      */ 
  10.     // 。 
  11.  
  12.     acquireVelocityTrackerAndAddMovement(ev); 
  13.  
  14.     // Skip touch handling if there are no pages to swipe 
  15.     //  , 。 
  16.     if (getChildCount() <= 0return super.onInterceptTouchEvent(ev); 
  17.  
  18.     /* 
  19.      * Shortcut the most recurring case: the user is in the dragging 
  20.      * state and he is moving his finger.  We want to intercept this 
  21.      * motion. 
  22.      * shortcut : , , 。 
  23.      *  
  24.      */ 
  25.     final int action = ev.getAction(); 
  26.     // MOVE , Touch  
  27.     if ((action == MotionEvent.ACTION_MOVE) &&               
  28.             (mTouchState == TOUCH_STATE_SCROLLING)) { 
  29.         return true
  30.     } 
  31.  
  32.     switch (action & MotionEvent.ACTION_MASK) { 
  33.         case MotionEvent.ACTION_MOVE: { 
  34.             /* 
  35.              * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check 
  36.              * whether the user has moved far enough from his original down touch. 
  37.              *  mIsBeingDragged==false , ,  
  38.              */ 
  39.             if (mActivePointerId != INVALID_POINTER) { 
  40.                 // , lastMotionX mTouchState 。 。 
  41.                 determineScrollingStart(ev); 
  42.                 break
  43.             } 
  44.             // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN 
  45.             // event. in that case, treat the first occurence of a move event as a ACTION_DOWN 
  46.             // i.e. fall through to the next case (don't break) 
  47.             // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events 
  48.             // while it's small- this was causing a crash before we checked for INVALID_POINTER) 
  49.             //  mActivePointerId   INVALID_POINTER, ACTION_DOWN 。 ,  
  50.             //  ACTION——DOWN , 。 
  51.             //  workspace ACTION_DOWN , workspace 。                 
  52.         } 
  53.  
  54.         case MotionEvent.ACTION_DOWN: { 
  55.             final float x = ev.getX(); 
  56.             final float y = ev.getY(); 
  57.             // Remember location of down touch 
  58.             //   
  59.             mDownMotionX = x; 
  60.             mLastMotionX = x; 
  61.             mLastMotionY = y; 
  62.             mLastMotionXRemainder = 0
  63.             mTotalMotionX = 0
  64.             //Return the pointer identifier associated with a particular pointer data index is this event.  
  65.             //The identifier tells you the actual pointer number associated with the data,  
  66.             //accounting for individual pointers going up and down since the start of the current gesture. 
  67.             // id, id , 。 
  68.             mActivePointerId = ev.getPointerId(0); 
  69.             mAllowLongPress = true
  70.  
  71.             /* 
  72.              * If being flinged and user touches the screen, initiate drag; 
  73.              * otherwise don't.  mScroller.isFinished should be false when 
  74.              * being flinged. 
  75.              *  , , 。 
  76.              *  mScroller.isFinished false. 
  77.              *  
  78.              */ 
  79.             final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX()); 
  80.              
  81.             final boolean finishedScrolling = (mScroller.isFinished() || xDist 
  82.             if (finishedScrolling) { 
  83.                 // TOUCH_STATE_REST  
  84.                 mTouchState = TOUCH_STATE_REST; 
  85.                 //  
  86.                 mScroller.abortAnimation(); 
  87.             } else { 
  88.                 // TOUCH_STATE_SCROLLING 
  89.                 mTouchState = TOUCH_STATE_SCROLLING; 
  90.             } 
  91.  
  92.             // check if this can be the beginning of a tap on the side of the pages 
  93.             // to scroll the current page 
  94.             //  。                 
  95.             if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) { 
  96.                 if (getChildCount() > 0) { 
  97.                     // ,  
  98.                     if (hitsPreviousPage(x, y)) { 
  99.                         mTouchState = TOUCH_STATE_PREV_PAGE; 
  100.                     } else if (hitsNextPage(x, y)) { 
  101.                         mTouchState = TOUCH_STATE_NEXT_PAGE; 
  102.                     } 
  103.                 } 
  104.             } 
  105.             break
  106.         } 
  107.  
  108.         case MotionEvent.ACTION_UP: 
  109.         case MotionEvent.ACTION_CANCEL: 
  110.             // ,  
  111.             mTouchState = TOUCH_STATE_REST; 
  112.             mAllowLongPress = false
  113.             mActivePointerId = INVALID_POINTER; 
  114.             //  
  115.             releaseVelocityTracker(); 
  116.             break
  117.  
  118.         case MotionEvent.ACTION_POINTER_UP: 
  119.             onSecondaryPointerUp(ev); 
  120.             releaseVelocityTracker(); 
  121.             break
  122.     } 
  123.  
  124.     /* 
  125.      * The only time we want to intercept motion events is if we are in the 
  126.      * drag mode. 
  127.      *   
  128.      */ 
  129.     if(DEBUG) Log.d(TAG, "onInterceptTouchEvent "+(mTouchState != TOUCH_STATE_REST)); 
  130.     // mTouchState TOUCH_STATE_REST,  
  131.     return mTouchState != TOUCH_STATE_REST;