1 /* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.launcher3; 18 19 import android.animation.Animator; 20 import android.animation.AnimatorListenerAdapter; 21 import android.animation.AnimatorSet; 22 import android.animation.ObjectAnimator; 23 import android.animation.TimeInterpolator; 24 import android.animation.ValueAnimator; 25 import android.animation.ValueAnimator.AnimatorUpdateListener; 26 import android.content.Context; 27 import android.content.res.TypedArray; 28 import android.graphics.Canvas; 29 import android.graphics.Matrix; 30 import android.graphics.PointF; 31 import android.graphics.Rect; 32 import android.os.Bundle; 33 import android.os.Parcel; 34 import android.os.Parcelable; 35 import android.support.v4.view.accessibility.AccessibilityEventCompat; 36 import android.util.AttributeSet; 37 import android.util.DisplayMetrics; 38 import android.util.Log; 39 import android.view.InputDevice; 40 import android.view.KeyEvent; 41 import android.view.MotionEvent; 42 import android.view.VelocityTracker; 43 import android.view.View; 44 import android.view.ViewConfiguration; 45 import android.view.ViewGroup; 46 import android.view.ViewParent; 47 import android.view.accessibility.AccessibilityEvent; 48 import android.view.accessibility.AccessibilityManager; 49 import android.view.accessibility.AccessibilityNodeInfo; 50 import android.view.animation.AnimationUtils; 51 import android.view.animation.DecelerateInterpolator; 52 import android.view.animation.Interpolator; 53 import android.view.animation.LinearInterpolator; 54 import android.widget.Scroller; 55 56 import java.util.ArrayList; 57 58 interface Page { 59 public int getPageChildCount(); 60 public View getChildOnPageAt(int i); 61 public void removeAllViewsOnPage(); 62 public void removeViewOnPageAt(int i); 63 public int indexOfChildOnPage(View v); 64 } 65 66 /** 67 * An abstraction of the original Workspace which supports browsing through a 68 * sequential list of "pages" 69 */ 70 public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener { 71 private static final String TAG = "PagedView"; 72 private static final boolean DEBUG = false; 73 protected static final int INVALID_PAGE = -1; 74 75 // the min drag distance for a fling to register, to prevent random page shifts 76 private static final int MIN_LENGTH_FOR_FLING = 25; 77 78 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750; 79 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950; 80 protected static final float NANOTIME_DIV = 1000000000.0f; 81 82 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2; 83 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f; 84 85 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f; 86 // The page is moved more than halfway, automatically move to the next page on touch up. 87 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f; 88 89 // The following constants need to be scaled based on density. The scaled versions will be 90 // assigned to the corresponding member variables below. 91 private static final int FLING_THRESHOLD_VELOCITY = 500; 92 private static final int MIN_SNAP_VELOCITY = 1500; 93 private static final int MIN_FLING_VELOCITY = 250; 94 95 // We are disabling touch interaction of the widget region for factory ROM. 96 private static final boolean DISABLE_TOUCH_INTERACTION = false; 97 private static final boolean DISABLE_TOUCH_SIDE_PAGES = true; 98 private static final boolean DISABLE_FLING_TO_DELETE = true; 99 100 public static final int INVALID_RESTORE_PAGE = -1001; 101 102 private boolean mFreeScroll = false; 103 private int mFreeScrollMinScrollX = -1; 104 private int mFreeScrollMaxScrollX = -1; 105 106 static final int AUTOMATIC_PAGE_SPACING = -1; 107 108 protected int mFlingThresholdVelocity; 109 protected int mMinFlingVelocity; 110 protected int mMinSnapVelocity; 111 112 protected float mDensity; 113 protected float mSmoothingTime; 114 protected float mTouchX; 115 116 protected boolean mFirstLayout = true; 117 private int mNormalChildHeight; 118 119 protected int mCurrentPage; 120 protected int mRestorePage = INVALID_RESTORE_PAGE; 121 protected int mChildCountOnLastLayout; 122 123 protected int mNextPage = INVALID_PAGE; 124 protected int mMaxScrollX; 125 protected Scroller mScroller; 126 private VelocityTracker mVelocityTracker; 127 128 private float mParentDownMotionX; 129 private float mParentDownMotionY; 130 private float mDownMotionX; 131 private float mDownMotionY; 132 private float mDownScrollX; 133 private float mDragViewBaselineLeft; 134 protected float mLastMotionX; 135 protected float mLastMotionXRemainder; 136 protected float mLastMotionY; 137 protected float mTotalMotionX; 138 private int mLastScreenCenter = -1; 139 140 private boolean mCancelTap; 141 142 private int[] mPageScrolls; 143 144 protected final static int TOUCH_STATE_REST = 0; 145 protected final static int TOUCH_STATE_SCROLLING = 1; 146 protected final static int TOUCH_STATE_PREV_PAGE = 2; 147 protected final static int TOUCH_STATE_NEXT_PAGE = 3; 148 protected final static int TOUCH_STATE_REORDERING = 4; 149 150 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f; 151 152 protected int mTouchState = TOUCH_STATE_REST; 153 protected boolean mForceScreenScrolled = false; 154 155 protected OnLongClickListener mLongClickListener; 156 157 protected int mTouchSlop; 158 private int mPagingTouchSlop; 159 private int mMaximumVelocity; 160 protected int mPageSpacing; 161 protected int mPageLayoutPaddingTop; 162 protected int mPageLayoutPaddingBottom; 163 protected int mPageLayoutPaddingLeft; 164 protected int mPageLayoutPaddingRight; 165 protected int mPageLayoutWidthGap; 166 protected int mPageLayoutHeightGap; 167 protected int mCellCountX = 0; 168 protected int mCellCountY = 0; 169 protected boolean mCenterPagesVertically; 170 protected boolean mAllowOverScroll = true; 171 protected int mUnboundedScrollX; 172 protected int[] mTempVisiblePagesRange = new int[2]; 173 protected boolean mForceDrawAllChildrenNextFrame; 174 175 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise 176 // it is equal to the scaled overscroll position. We use a separate value so as to prevent 177 // the screens from continuing to translate beyond the normal bounds. 178 protected int mOverScrollX; 179 180 protected static final int INVALID_POINTER = -1; 181 182 protected int mActivePointerId = INVALID_POINTER; 183 184 private PageSwitchListener mPageSwitchListener; 185 186 protected ArrayList<Boolean> mDirtyPageContent; 187 188 // If true, syncPages and syncPageItems will be called to refresh pages 189 protected boolean mContentIsRefreshable = true; 190 191 // If true, modify alpha of neighboring pages as user scrolls left/right 192 protected boolean mFadeInAdjacentScreens = false; 193 194 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding 195 // to switch to a new page 196 protected boolean mUsePagingTouchSlop = true; 197 198 // If true, the subclass should directly update scrollX itself in its computeScroll method 199 // (SmoothPagedView does this) 200 protected boolean mDeferScrollUpdate = false; 201 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false; 202 203 protected boolean mIsPageMoving = false; 204 205 // All syncs and layout passes are deferred until data is ready. 206 protected boolean mIsDataReady = false; 207 208 protected boolean mAllowLongPress = true; 209 210 // Page Indicator 211 private int mPageIndicatorViewId; 212 private PageIndicator mPageIndicator; 213 private boolean mAllowPagedViewAnimations = true; 214 215 // The viewport whether the pages are to be contained (the actual view may be larger than the 216 // viewport) 217 private Rect mViewport = new Rect(); 218 219 // Reordering 220 // We use the min scale to determine how much to expand the actually PagedView measured 221 // dimensions such that when we are zoomed out, the view is not clipped 222 private int REORDERING_DROP_REPOSITION_DURATION = 200; 223 protected int REORDERING_REORDER_REPOSITION_DURATION = 300; 224 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250; 225 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80; 226 private float mMinScale = 1f; 227 private boolean mUseMinScale = false; 228 protected View mDragView; 229 protected AnimatorSet mZoomInOutAnim; 230 private Runnable mSidePageHoverRunnable; 231 private int mSidePageHoverIndex = -1; 232 // This variable's scope is only for the duration of startReordering() and endReordering() 233 private boolean mReorderingStarted = false; 234 // This variable's scope is for the duration of startReordering() and after the zoomIn() 235 // animation after endReordering() 236 private boolean mIsReordering; 237 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition 238 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2; 239 private int mPostReorderingPreZoomInRemainingAnimationCount; 240 private Runnable mPostReorderingPreZoomInRunnable; 241 242 // Convenience/caching 243 private Matrix mTmpInvMatrix = new Matrix(); 244 private float[] mTmpPoint = new float[2]; 245 private int[] mTmpIntPoint = new int[2]; 246 private Rect mTmpRect = new Rect(); 247 private Rect mAltTmpRect = new Rect(); 248 249 // Fling to delete 250 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350; 251 private float FLING_TO_DELETE_FRICTION = 0.035f; 252 // The degrees specifies how much deviation from the up vector to still consider a fling "up" 253 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f; 254 protected int mFlingToDeleteThresholdVelocity = -1400; 255 // Drag to delete 256 private boolean mDeferringForDelete = false; 257 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250; 258 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350; 259 260 // Drop to delete 261 private View mDeleteDropTarget; 262 263 private boolean mAutoComputePageSpacing = false; 264 private boolean mRecomputePageSpacing = false; 265 266 // Bouncer 267 private boolean mTopAlignPageWhenShrinkingForBouncer = false; 268 269 protected final Rect mInsets = new Rect(); 270 271 protected int mFirstChildLeft; 272 273 public interface PageSwitchListener { 274 void onPageSwitch(View newPage, int newPageIndex); 275 } 276 277 public PagedView(Context context) { 278 this(context, null); 279 } 280 281 public PagedView(Context context, AttributeSet attrs) { 282 this(context, attrs, 0); 283 } 284 285 public PagedView(Context context, AttributeSet attrs, int defStyle) { 286 super(context, attrs, defStyle); 287 288 TypedArray a = context.obtainStyledAttributes(attrs, 289 R.styleable.PagedView, defStyle, 0); 290 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0)); 291 if (mPageSpacing < 0) { 292 mAutoComputePageSpacing = mRecomputePageSpacing = true; 293 } 294 mPageLayoutPaddingTop = a.getDimensionPixelSize( 295 R.styleable.PagedView_pageLayoutPaddingTop, 0); 296 mPageLayoutPaddingBottom = a.getDimensionPixelSize( 297 R.styleable.PagedView_pageLayoutPaddingBottom, 0); 298 mPageLayoutPaddingLeft = a.getDimensionPixelSize( 299 R.styleable.PagedView_pageLayoutPaddingLeft, 0); 300 mPageLayoutPaddingRight = a.getDimensionPixelSize( 301 R.styleable.PagedView_pageLayoutPaddingRight, 0); 302 mPageLayoutWidthGap = a.getDimensionPixelSize( 303 R.styleable.PagedView_pageLayoutWidthGap, 0); 304 mPageLayoutHeightGap = a.getDimensionPixelSize( 305 R.styleable.PagedView_pageLayoutHeightGap, 0); 306 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1); 307 a.recycle(); 308 309 setHapticFeedbackEnabled(false); 310 init(); 311 } 312 313 /** 314 * Initializes various states for this workspace. 315 */ 316 protected void init() { 317 mDirtyPageContent = new ArrayList<Boolean>(); 318 mDirtyPageContent.ensureCapacity(32); 319 mScroller = new Scroller(getContext(), new ScrollInterpolator()); 320 mCurrentPage = 0; 321 mCenterPagesVertically = true; 322 323 final ViewConfiguration configuration = ViewConfiguration.get(getContext()); 324 mTouchSlop = configuration.getScaledPagingTouchSlop(); 325 mPagingTouchSlop = configuration.getScaledPagingTouchSlop(); 326 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); 327 mDensity = getResources().getDisplayMetrics().density; 328 329 // Scale the fling-to-delete threshold by the density 330 mFlingToDeleteThresholdVelocity = 331 (int) (mFlingToDeleteThresholdVelocity * mDensity); 332 333 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity); 334 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity); 335 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity); 336 setOnHierarchyChangeListener(this); 337 } 338 339 protected void onAttachedToWindow() { 340 super.onAttachedToWindow(); 341 342 // Hook up the page indicator 343 ViewGroup parent = (ViewGroup) getParent(); 344 if (mPageIndicator == null && mPageIndicatorViewId > -1) { 345 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId); 346 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations); 347 348 ArrayList<PageIndicator.PageMarkerResources> markers = 349 new ArrayList<PageIndicator.PageMarkerResources>(); 350 for (int i = 0; i < getChildCount(); ++i) { 351 markers.add(getPageIndicatorMarker(i)); 352 } 353 354 mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations); 355 356 OnClickListener listener = getPageIndicatorClickListener(); 357 if (listener != null) { 358 mPageIndicator.setOnClickListener(listener); 359 } 360 mPageIndicator.setContentDescription(getPageIndicatorDescription()); 361 } 362 } 363 364 protected String getPageIndicatorDescription() { 365 return getCurrentPageDescription(); 366 } 367 368 protected OnClickListener getPageIndicatorClickListener() { 369 return null; 370 } 371 372 protected void onDetachedFromWindow() { 373 // Unhook the page indicator 374 mPageIndicator = null; 375 } 376 377 void setDeleteDropTarget(View v) { 378 mDeleteDropTarget = v; 379 } 380 381 // Convenience methods to map points from self to parent and vice versa 382 float[] mapPointFromViewToParent(View v, float x, float y) { 383 mTmpPoint[0] = x; 384 mTmpPoint[1] = y; 385 v.getMatrix().mapPoints(mTmpPoint); 386 mTmpPoint[0] += v.getLeft(); 387 mTmpPoint[1] += v.getTop(); 388 return mTmpPoint; 389 } 390 float[] mapPointFromParentToView(View v, float x, float y) { 391 mTmpPoint[0] = x - v.getLeft(); 392 mTmpPoint[1] = y - v.getTop(); 393 v.getMatrix().invert(mTmpInvMatrix); 394 mTmpInvMatrix.mapPoints(mTmpPoint); 395 return mTmpPoint; 396 } 397 398 void updateDragViewTranslationDuringDrag() { 399 if (mDragView != null) { 400 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) + 401 (mDragViewBaselineLeft - mDragView.getLeft()); 402 float y = mLastMotionY - mDownMotionY; 403 mDragView.setTranslationX(x); 404 mDragView.setTranslationY(y); 405 406 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): " 407 + x + ", " + y); 408 } 409 } 410 411 public void setMinScale(float f) { 412 mMinScale = f; 413 mUseMinScale = true; 414 requestLayout(); 415 } 416 417 @Override 418 public void setScaleX(float scaleX) { 419 super.setScaleX(scaleX); 420 if (isReordering(true)) { 421 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY); 422 mLastMotionX = p[0]; 423 mLastMotionY = p[1]; 424 updateDragViewTranslationDuringDrag(); 425 } 426 } 427 428 // Convenience methods to get the actual width/height of the PagedView (since it is measured 429 // to be larger to account for the minimum possible scale) 430 int getViewportWidth() { 431 return mViewport.width(); 432 } 433 int getViewportHeight() { 434 return mViewport.height(); 435 } 436 437 // Convenience methods to get the offset ASSUMING that we are centering the pages in the 438 // PagedView both horizontally and vertically 439 int getViewportOffsetX() { 440 return (getMeasuredWidth() - getViewportWidth()) / 2; 441 } 442 443 int getViewportOffsetY() { 444 return (getMeasuredHeight() - getViewportHeight()) / 2; 445 } 446 447 PageIndicator getPageIndicator() { 448 return mPageIndicator; 449 } 450 protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) { 451 return new PageIndicator.PageMarkerResources(); 452 } 453 454 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) { 455 mPageSwitchListener = pageSwitchListener; 456 if (mPageSwitchListener != null) { 457 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage); 458 } 459 } 460 461 /** 462 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api. 463 */ 464 public boolean isLayoutRtl() { 465 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 466 } 467 468 /** 469 * Called by subclasses to mark that data is ready, and that we can begin loading and laying 470 * out pages. 471 */ 472 protected void setDataIsReady() { 473 mIsDataReady = true; 474 } 475 476 protected boolean isDataReady() { 477 return mIsDataReady; 478 } 479 480 /** 481 * Returns the index of the currently displayed page. 482 * 483 * @return The index of the currently displayed page. 484 */ 485 int getCurrentPage() { 486 return mCurrentPage; 487 } 488 489 int getNextPage() { 490 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 491 } 492 493 int getPageCount() { 494 return getChildCount(); 495 } 496 497 View getPageAt(int index) { 498 return getChildAt(index); 499 } 500 501 protected int indexToPage(int index) { 502 return index; 503 } 504 505 /** 506 * Updates the scroll of the current page immediately to its final scroll position. We use this 507 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of 508 * the previous tab page. 509 */ 510 protected void updateCurrentPageScroll() { 511 // If the current page is invalid, just reset the scroll position to zero 512 int newX = 0; 513 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) { 514 newX = getScrollForPage(mCurrentPage); 515 } 516 scrollTo(newX, 0); 517 mScroller.setFinalX(newX); 518 mScroller.forceFinished(true); 519 } 520 521 /** 522 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation 523 * ends, {@link #resumeScrolling()} should be called, along with 524 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling. 525 */ 526 void pauseScrolling() { 527 mScroller.forceFinished(true); 528 } 529 530 /** 531 * Enables scrolling again. 532 * @see #pauseScrolling() 533 */ 534 void resumeScrolling() { 535 } 536 /** 537 * Sets the current page. 538 */ 539 void setCurrentPage(int currentPage) { 540 if (!mScroller.isFinished()) { 541 mScroller.abortAnimation(); 542 // We need to clean up the next page here to avoid computeScrollHelper from 543 // updating current page on the pass. 544 mNextPage = INVALID_PAGE; 545 } 546 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the 547 // the default 548 if (getChildCount() == 0) { 549 return; 550 } 551 mForceScreenScrolled = true; 552 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1)); 553 updateCurrentPageScroll(); 554 notifyPageSwitchListener(); 555 invalidate(); 556 } 557 558 /** 559 * The restore page will be set in place of the current page at the next (likely first) 560 * layout. 561 */ 562 void setRestorePage(int restorePage) { 563 mRestorePage = restorePage; 564 } 565 566 protected void notifyPageSwitchListener() { 567 if (mPageSwitchListener != null) { 568 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage); 569 } 570 571 // Update the page indicator (when we aren't reordering) 572 if (mPageIndicator != null && !isReordering(false)) { 573 mPageIndicator.setActiveMarker(getNextPage()); 574 } 575 } 576 protected void pageBeginMoving() { 577 if (!mIsPageMoving) { 578 mIsPageMoving = true; 579 onPageBeginMoving(); 580 } 581 } 582 583 protected void pageEndMoving() { 584 if (mIsPageMoving) { 585 mIsPageMoving = false; 586 onPageEndMoving(); 587 } 588 } 589 590 protected boolean isPageMoving() { 591 return mIsPageMoving; 592 } 593 594 // a method that subclasses can override to add behavior 595 protected void onPageBeginMoving() { 596 } 597 598 // a method that subclasses can override to add behavior 599 protected void onPageEndMoving() { 600 } 601 602 /** 603 * Registers the specified listener on each page contained in this workspace. 604 * 605 * @param l The listener used to respond to long clicks. 606 */ 607 @Override 608 public void setOnLongClickListener(OnLongClickListener l) { 609 mLongClickListener = l; 610 final int count = getPageCount(); 611 for (int i = 0; i < count; i++) { 612 getPageAt(i).setOnLongClickListener(l); 613 } 614 super.setOnLongClickListener(l); 615 } 616 617 @Override 618 public void scrollBy(int x, int y) { 619 scrollTo(mUnboundedScrollX + x, getScrollY() + y); 620 } 621 622 @Override 623 public void scrollTo(int x, int y) { 624 // In free scroll mode, we clamp the scrollX 625 if (mFreeScroll) { 626 x = Math.min(x, mFreeScrollMaxScrollX); 627 x = Math.max(x, mFreeScrollMinScrollX); 628 } 629 630 final boolean isRtl = isLayoutRtl(); 631 mUnboundedScrollX = x; 632 633 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0); 634 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX); 635 if (isXBeforeFirstPage) { 636 super.scrollTo(0, y); 637 if (mAllowOverScroll) { 638 if (isRtl) { 639 overScroll(x - mMaxScrollX); 640 } else { 641 overScroll(x); 642 } 643 } 644 } else if (isXAfterLastPage) { 645 super.scrollTo(mMaxScrollX, y); 646 if (mAllowOverScroll) { 647 if (isRtl) { 648 overScroll(x); 649 } else { 650 overScroll(x - mMaxScrollX); 651 } 652 } 653 } else { 654 mOverScrollX = x; 655 super.scrollTo(x, y); 656 } 657 658 mTouchX = x; 659 mSmoothingTime = System.nanoTime() / NANOTIME_DIV; 660 661 // Update the last motion events when scrolling 662 if (isReordering(true)) { 663 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY); 664 mLastMotionX = p[0]; 665 mLastMotionY = p[1]; 666 updateDragViewTranslationDuringDrag(); 667 } 668 } 669 670 private void sendScrollAccessibilityEvent() { 671 AccessibilityManager am = 672 (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); 673 if (am.isEnabled()) { 674 AccessibilityEvent ev = 675 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED); 676 ev.setItemCount(getChildCount()); 677 ev.setFromIndex(mCurrentPage); 678 679 final int action; 680 if (getNextPage() >= mCurrentPage) { 681 action = AccessibilityNodeInfo.ACTION_SCROLL_FORWARD; 682 } else { 683 action = AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD; 684 } 685 686 ev.setAction(action); 687 sendAccessibilityEventUnchecked(ev); 688 } 689 } 690 691 // we moved this functionality to a helper function so SmoothPagedView can reuse it 692 protected boolean computeScrollHelper() { 693 if (mScroller.computeScrollOffset()) { 694 // Don't bother scrolling if the page does not need to be moved 695 if (getScrollX() != mScroller.getCurrX() 696 || getScrollY() != mScroller.getCurrY() 697 || mOverScrollX != mScroller.getCurrX()) { 698 float scaleX = mFreeScroll ? getScaleX() : 1f; 699 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX)); 700 scrollTo(scrollX, mScroller.getCurrY()); 701 } 702 invalidate(); 703 return true; 704 } else if (mNextPage != INVALID_PAGE) { 705 sendScrollAccessibilityEvent(); 706 707 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1)); 708 mNextPage = INVALID_PAGE; 709 notifyPageSwitchListener(); 710 711 // Load the associated pages if necessary 712 if (mDeferLoadAssociatedPagesUntilScrollCompletes) { 713 loadAssociatedPages(mCurrentPage); 714 mDeferLoadAssociatedPagesUntilScrollCompletes = false; 715 } 716 717 // We don't want to trigger a page end moving unless the page has settled 718 // and the user has stopped scrolling 719 if (mTouchState == TOUCH_STATE_REST) { 720 pageEndMoving(); 721 } 722 723 onPostReorderingAnimationCompleted(); 724 AccessibilityManager am = (AccessibilityManager) 725 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); 726 if (am.isEnabled()) { 727 // Notify the user when the page changes 728 announceForAccessibility(getCurrentPageDescription()); 729 } 730 return true; 731 } 732 return false; 733 } 734 735 @Override 736 public void computeScroll() { 737 computeScrollHelper(); 738 } 739 740 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) { 741 return mTopAlignPageWhenShrinkingForBouncer; 742 } 743 744 public static class LayoutParams extends ViewGroup.LayoutParams { 745 public boolean isFullScreenPage = false; 746 747 /** 748 * {@inheritDoc} 749 */ 750 public LayoutParams(int width, int height) { 751 super(width, height); 752 } 753 754 public LayoutParams(ViewGroup.LayoutParams source) { 755 super(source); 756 } 757 } 758 759 protected LayoutParams generateDefaultLayoutParams() { 760 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 761 } 762 763 public void addFullScreenPage(View page) { 764 LayoutParams lp = generateDefaultLayoutParams(); 765 lp.isFullScreenPage = true; 766 super.addView(page, 0, lp); 767 } 768 769 public int getNormalChildHeight() { 770 return mNormalChildHeight; 771 } 772 773 @Override 774 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 775 if (!mIsDataReady || getChildCount() == 0) { 776 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 777 return; 778 } 779 780 // We measure the dimensions of the PagedView to be larger than the pages so that when we 781 // zoom out (and scale down), the view is still contained in the parent 782 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 783 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 784 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 785 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 786 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the 787 // viewport, we can be at most one and a half screens offset once we scale down 788 DisplayMetrics dm = getResources().getDisplayMetrics(); 789 int maxSize = Math.max(dm.widthPixels, dm.heightPixels + mInsets.top + mInsets.bottom); 790 791 int parentWidthSize, parentHeightSize; 792 int scaledWidthSize, scaledHeightSize; 793 if (mUseMinScale) { 794 parentWidthSize = (int) (1.5f * maxSize); 795 parentHeightSize = maxSize; 796 scaledWidthSize = (int) (parentWidthSize / mMinScale); 797 scaledHeightSize = (int) (parentHeightSize / mMinScale); 798 } else { 799 scaledWidthSize = widthSize; 800 scaledHeightSize = heightSize; 801 } 802 mViewport.set(0, 0, widthSize, heightSize); 803 804 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) { 805 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 806 return; 807 } 808 809 // Return early if we aren't given a proper dimension 810 if (widthSize <= 0 || heightSize <= 0) { 811 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 812 return; 813 } 814 815 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case 816 * of the All apps view on XLarge displays to not take up more space then it needs. Width 817 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect 818 * each page to have the same width. 819 */ 820 final int verticalPadding = getPaddingTop() + getPaddingBottom(); 821 final int horizontalPadding = getPaddingLeft() + getPaddingRight(); 822 823 // The children are given the same width and height as the workspace 824 // unless they were set to WRAP_CONTENT 825 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize); 826 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize); 827 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize); 828 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding); 829 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding); 830 final int childCount = getChildCount(); 831 for (int i = 0; i < childCount; i++) { 832 // disallowing padding in paged view (just pass 0) 833 final View child = getPageAt(i); 834 if (child.getVisibility() != GONE) { 835 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 836 837 int childWidthMode; 838 int childHeightMode; 839 int childWidth; 840 int childHeight; 841 842 if (!lp.isFullScreenPage) { 843 if (lp.width == LayoutParams.WRAP_CONTENT) { 844 childWidthMode = MeasureSpec.AT_MOST; 845 } else { 846 childWidthMode = MeasureSpec.EXACTLY; 847 } 848 849 if (lp.height == LayoutParams.WRAP_CONTENT) { 850 childHeightMode = MeasureSpec.AT_MOST; 851 } else { 852 childHeightMode = MeasureSpec.EXACTLY; 853 } 854 855 childWidth = widthSize - horizontalPadding; 856 childHeight = heightSize - verticalPadding - mInsets.top - mInsets.bottom; 857 mNormalChildHeight = childHeight; 858 859 } else { 860 childWidthMode = MeasureSpec.EXACTLY; 861 childHeightMode = MeasureSpec.EXACTLY; 862 863 if (mUseMinScale) { 864 childWidth = getViewportWidth(); 865 childHeight = getViewportHeight(); 866 } else { 867 childWidth = widthSize - getPaddingLeft() - getPaddingRight(); 868 childHeight = heightSize - getPaddingTop() - getPaddingBottom(); 869 } 870 } 871 872 final int childWidthMeasureSpec = 873 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode); 874 final int childHeightMeasureSpec = 875 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode); 876 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 877 } 878 } 879 setMeasuredDimension(scaledWidthSize, scaledHeightSize); 880 881 if (childCount > 0) { 882 // Calculate the variable page spacing if necessary 883 if (mAutoComputePageSpacing && mRecomputePageSpacing) { 884 // The gap between pages in the PagedView should be equal to the gap from the page 885 // to the edge of the screen (so it is not visible in the current screen). To 886 // account for unequal padding on each side of the paged view, we take the maximum 887 // of the left/right gap and use that as the gap between each page. 888 int offset = (getViewportWidth() - getChildWidth(0)) / 2; 889 int spacing = Math.max(offset, widthSize - offset - 890 getChildAt(0).getMeasuredWidth()); 891 setPageSpacing(spacing); 892 mRecomputePageSpacing = false; 893 } 894 } 895 } 896 897 public void setPageSpacing(int pageSpacing) { 898 mPageSpacing = pageSpacing; 899 requestLayout(); 900 } 901 902 protected int getFirstChildLeft() { 903 return mFirstChildLeft; 904 } 905 906 @Override 907 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 908 if (!mIsDataReady || getChildCount() == 0) { 909 return; 910 } 911 912 if (DEBUG) Log.d(TAG, "PagedView.onLayout()"); 913 final int childCount = getChildCount(); 914 915 int screenWidth = getViewportWidth(); 916 917 int offsetX = getViewportOffsetX(); 918 int offsetY = getViewportOffsetY(); 919 920 // Update the viewport offsets 921 mViewport.offset(offsetX, offsetY); 922 923 final boolean isRtl = isLayoutRtl(); 924 925 final int startIndex = isRtl ? childCount - 1 : 0; 926 final int endIndex = isRtl ? -1 : childCount; 927 final int delta = isRtl ? -1 : 1; 928 929 int verticalPadding = getPaddingTop() + getPaddingBottom(); 930 931 int childLeft = mFirstChildLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2; 932 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) { 933 mPageScrolls = new int[getChildCount()]; 934 } 935 936 for (int i = startIndex; i != endIndex; i += delta) { 937 final View child = getPageAt(i); 938 if (child.getVisibility() != View.GONE) { 939 LayoutParams lp = (LayoutParams) child.getLayoutParams(); 940 int childTop; 941 if (lp.isFullScreenPage) { 942 childTop = offsetY; 943 } else { 944 childTop = offsetY + getPaddingTop() + mInsets.top; 945 if (mCenterPagesVertically) { 946 childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2; 947 } 948 } 949 950 final int childWidth = child.getMeasuredWidth(); 951 final int childHeight = child.getMeasuredHeight(); 952 953 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop); 954 child.layout(childLeft, childTop, 955 childLeft + child.getMeasuredWidth(), childTop + childHeight); 956 957 // We assume the left and right padding are equal, and hence center the pages 958 // horizontally 959 int scrollOffset = (getViewportWidth() - childWidth) / 2; 960 mPageScrolls[i] = childLeft - scrollOffset - offsetX; 961 962 if (i != endIndex - delta) { 963 childLeft += childWidth + scrollOffset; 964 int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2; 965 childLeft += nextScrollOffset; 966 } 967 } 968 } 969 970 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) { 971 setHorizontalScrollBarEnabled(false); 972 updateCurrentPageScroll(); 973 setHorizontalScrollBarEnabled(true); 974 mFirstLayout = false; 975 } 976 977 if (childCount > 0) { 978 final int index = isLayoutRtl() ? 0 : childCount - 1; 979 mMaxScrollX = getScrollForPage(index); 980 } else { 981 mMaxScrollX = 0; 982 } 983 984 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() && 985 !mDeferringForDelete) { 986 if (mRestorePage != INVALID_RESTORE_PAGE) { 987 setCurrentPage(mRestorePage); 988 mRestorePage = INVALID_RESTORE_PAGE; 989 } else { 990 setCurrentPage(getNextPage()); 991 } 992 } 993 mChildCountOnLastLayout = getChildCount(); 994 995 if (isReordering(true)) { 996 updateDragViewTranslationDuringDrag(); 997 } 998 } 999 1000 protected void screenScrolled(int screenCenter) { 1001 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX; 1002 1003 if (mFadeInAdjacentScreens && !isInOverscroll) { 1004 for (int i = 0; i < getChildCount(); i++) { 1005 View child = getChildAt(i); 1006 if (child != null) { 1007 float scrollProgress = getScrollProgress(screenCenter, child, i); 1008 float alpha = 1 - Math.abs(scrollProgress); 1009 child.setAlpha(alpha); 1010 } 1011 } 1012 invalidate(); 1013 } 1014 } 1015 1016 protected void enablePagedViewAnimations() { 1017 mAllowPagedViewAnimations = true; 1018 1019 } 1020 protected void disablePagedViewAnimations() { 1021 mAllowPagedViewAnimations = false; 1022 } 1023 1024 @Override 1025 public void onChildViewAdded(View parent, View child) { 1026 // Update the page indicator, we don't update the page indicator as we 1027 // add/remove pages 1028 if (mPageIndicator != null && !isReordering(false)) { 1029 int pageIndex = indexOfChild(child); 1030 mPageIndicator.addMarker(pageIndex, 1031 getPageIndicatorMarker(pageIndex), 1032 mAllowPagedViewAnimations); 1033 } 1034 1035 // This ensures that when children are added, they get the correct transforms / alphas 1036 // in accordance with any scroll effects. 1037 mForceScreenScrolled = true; 1038 mRecomputePageSpacing = true; 1039 updateFreescrollBounds(); 1040 invalidate(); 1041 } 1042 1043 @Override 1044 public void onChildViewRemoved(View parent, View child) { 1045 mForceScreenScrolled = true; 1046 updateFreescrollBounds(); 1047 invalidate(); 1048 } 1049 1050 private void removeMarkerForView(int index) { 1051 // Update the page indicator, we don't update the page indicator as we 1052 // add/remove pages 1053 if (mPageIndicator != null && !isReordering(false)) { 1054 mPageIndicator.removeMarker(index, mAllowPagedViewAnimations); 1055 } 1056 } 1057 1058 @Override 1059 public void removeView(View v) { 1060 // XXX: We should find a better way to hook into this before the view 1061 // gets removed form its parent... 1062 removeMarkerForView(indexOfChild(v)); 1063 super.removeView(v); 1064 } 1065 @Override 1066 public void removeViewInLayout(View v) { 1067 // XXX: We should find a better way to hook into this before the view 1068 // gets removed form its parent... 1069 removeMarkerForView(indexOfChild(v)); 1070 super.removeViewInLayout(v); 1071 } 1072 @Override 1073 public void removeViewAt(int index) { 1074 // XXX: We should find a better way to hook into this before the view 1075 // gets removed form its parent... 1076 removeViewAt(index); 1077 super.removeViewAt(index); 1078 } 1079 @Override 1080 public void removeAllViewsInLayout() { 1081 // Update the page indicator, we don't update the page indicator as we 1082 // add/remove pages 1083 if (mPageIndicator != null) { 1084 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations); 1085 } 1086 1087 super.removeAllViewsInLayout(); 1088 } 1089 1090 protected int getChildOffset(int index) { 1091 if (index < 0 || index > getChildCount() - 1) return 0; 1092 1093 int offset = getPageAt(index).getLeft() - getViewportOffsetX(); 1094 1095 return offset; 1096 } 1097 1098 protected void getOverviewModePages(int[] range) { 1099 range[0] = 0; 1100 range[1] = Math.max(0, getChildCount() - 1); 1101 } 1102 1103 protected void getVisiblePages(int[] range) { 1104 final int pageCount = getChildCount(); 1105 mTmpIntPoint[0] = mTmpIntPoint[1] = 0; 1106 1107 range[0] = -1; 1108 range[1] = -1; 1109 1110 if (pageCount > 0) { 1111 int viewportWidth = getViewportWidth(); 1112 int curScreen = 0; 1113 1114 int count = getChildCount(); 1115 for (int i = 0; i < count; i++) { 1116 View currPage = getPageAt(i); 1117 1118 mTmpIntPoint[0] = 0; 1119 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false); 1120 if (mTmpIntPoint[0] > viewportWidth) { 1121 if (range[0] == -1) { 1122 continue; 1123 } else { 1124 break; 1125 } 1126 } 1127 1128 mTmpIntPoint[0] = currPage.getMeasuredWidth(); 1129 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false); 1130 if (mTmpIntPoint[0] < 0) { 1131 if (range[0] == -1) { 1132 continue; 1133 } else { 1134 break; 1135 } 1136 } 1137 curScreen = i; 1138 if (range[0] < 0) { 1139 range[0] = curScreen; 1140 } 1141 } 1142 1143 range[1] = curScreen; 1144 } else { 1145 range[0] = -1; 1146 range[1] = -1; 1147 } 1148 } 1149 1150 protected boolean shouldDrawChild(View child) { 1151 return child.getAlpha() > 0 && child.getVisibility() == VISIBLE; 1152 } 1153 1154 @Override 1155 protected void dispatchDraw(Canvas canvas) { 1156 int halfScreenSize = getViewportWidth() / 2; 1157 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. 1158 // Otherwise it is equal to the scaled overscroll position. 1159 int screenCenter = mOverScrollX + halfScreenSize; 1160 1161 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) { 1162 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can 1163 // set it for the next frame 1164 mForceScreenScrolled = false; 1165 screenScrolled(screenCenter); 1166 mLastScreenCenter = screenCenter; 1167 } 1168 1169 // Find out which screens are visible; as an optimization we only call draw on them 1170 final int pageCount = getChildCount(); 1171 if (pageCount > 0) { 1172 getVisiblePages(mTempVisiblePagesRange); 1173 final int leftScreen = mTempVisiblePagesRange[0]; 1174 final int rightScreen = mTempVisiblePagesRange[1]; 1175 if (leftScreen != -1 && rightScreen != -1) { 1176 final long drawingTime = getDrawingTime(); 1177 // Clip to the bounds 1178 canvas.save(); 1179 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(), 1180 getScrollY() + getBottom() - getTop()); 1181 1182 // Draw all the children, leaving the drag view for last 1183 for (int i = pageCount - 1; i >= 0; i--) { 1184 final View v = getPageAt(i); 1185 if (v == mDragView) continue; 1186 if (mForceDrawAllChildrenNextFrame || 1187 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) { 1188 drawChild(canvas, v, drawingTime); 1189 } 1190 } 1191 // Draw the drag view on top (if there is one) 1192 if (mDragView != null) { 1193 drawChild(canvas, mDragView, drawingTime); 1194 } 1195 1196 mForceDrawAllChildrenNextFrame = false; 1197 canvas.restore(); 1198 } 1199 } 1200 } 1201 1202 @Override 1203 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { 1204 int page = indexToPage(indexOfChild(child)); 1205 if (page != mCurrentPage || !mScroller.isFinished()) { 1206 snapToPage(page); 1207 return true; 1208 } 1209 return false; 1210 } 1211 1212 @Override 1213 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { 1214 int focusablePage; 1215 if (mNextPage != INVALID_PAGE) { 1216 focusablePage = mNextPage; 1217 } else { 1218 focusablePage = mCurrentPage; 1219 } 1220 View v = getPageAt(focusablePage); 1221 if (v != null) { 1222 return v.requestFocus(direction, previouslyFocusedRect); 1223 } 1224 return false; 1225 } 1226 1227 @Override 1228 public boolean dispatchUnhandledMove(View focused, int direction) { 1229 // XXX-RTL: This will be fixed in a future CL 1230 if (direction == View.FOCUS_LEFT) { 1231 if (getCurrentPage() > 0) { 1232 snapToPage(getCurrentPage() - 1); 1233 return true; 1234 } 1235 } else if (direction == View.FOCUS_RIGHT) { 1236 if (getCurrentPage() < getPageCount() - 1) { 1237 snapToPage(getCurrentPage() + 1); 1238 return true; 1239 } 1240 } 1241 return super.dispatchUnhandledMove(focused, direction); 1242 } 1243 1244 @Override 1245 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 1246 // XXX-RTL: This will be fixed in a future CL 1247 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) { 1248 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode); 1249 } 1250 if (direction == View.FOCUS_LEFT) { 1251 if (mCurrentPage > 0) { 1252 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode); 1253 } 1254 } else if (direction == View.FOCUS_RIGHT){ 1255 if (mCurrentPage < getPageCount() - 1) { 1256 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode); 1257 } 1258 } 1259 } 1260 1261 /** 1262 * If one of our descendant views decides that it could be focused now, only 1263 * pass that along if it's on the current page. 1264 * 1265 * This happens when live folders requery, and if they're off page, they 1266 * end up calling requestFocus, which pulls it on page. 1267 */ 1268 @Override 1269 public void focusableViewAvailable(View focused) { 1270 View current = getPageAt(mCurrentPage); 1271 View v = focused; 1272 while (true) { 1273 if (v == current) { 1274 super.focusableViewAvailable(focused); 1275 return; 1276 } 1277 if (v == this) { 1278 return; 1279 } 1280 ViewParent parent = v.getParent(); 1281 if (parent instanceof View) { 1282 v = (View)v.getParent(); 1283 } else { 1284 return; 1285 } 1286 } 1287 } 1288 1289 /** 1290 * {@inheritDoc} 1291 */ 1292 @Override 1293 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 1294 if (disallowIntercept) { 1295 // We need to make sure to cancel our long press if 1296 // a scrollable widget takes over touch events 1297 final View currentPage = getPageAt(mCurrentPage); 1298 currentPage.cancelLongPress(); 1299 } 1300 super.requestDisallowInterceptTouchEvent(disallowIntercept); 1301 } 1302 1303 /** 1304 * Return true if a tap at (x, y) should trigger a flip to the previous page. 1305 */ 1306 protected boolean hitsPreviousPage(float x, float y) { 1307 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2; 1308 if (isLayoutRtl()) { 1309 return (x > (getViewportOffsetX() + getViewportWidth() - 1310 offset + mPageSpacing)); 1311 } 1312 return (x < getViewportOffsetX() + offset - mPageSpacing); 1313 } 1314 1315 /** 1316 * Return true if a tap at (x, y) should trigger a flip to the next page. 1317 */ 1318 protected boolean hitsNextPage(float x, float y) { 1319 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2; 1320 if (isLayoutRtl()) { 1321 return (x < getViewportOffsetX() + offset - mPageSpacing); 1322 } 1323 return (x > (getViewportOffsetX() + getViewportWidth() - 1324 offset + mPageSpacing)); 1325 } 1326 1327 /** Returns whether x and y originated within the buffered viewport */ 1328 private boolean isTouchPointInViewportWithBuffer(int x, int y) { 1329 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top, 1330 mViewport.right + mViewport.width() / 2, mViewport.bottom); 1331 return mTmpRect.contains(x, y); 1332 } 1333 1334 @Override 1335 public boolean onInterceptTouchEvent(MotionEvent ev) { 1336 if (DISABLE_TOUCH_INTERACTION) { 1337 return false; 1338 } 1339 1340 /* 1341 * This method JUST determines whether we want to intercept the motion. 1342 * If we return true, onTouchEvent will be called and we do the actual 1343 * scrolling there. 1344 */ 1345 acquireVelocityTrackerAndAddMovement(ev); 1346 1347 // Skip touch handling if there are no pages to swipe 1348 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev); 1349 1350 /* 1351 * Shortcut the most recurring case: the user is in the dragging 1352 * state and he is moving his finger. We want to intercept this 1353 * motion. 1354 */ 1355 final int action = ev.getAction(); 1356 if ((action == MotionEvent.ACTION_MOVE) && 1357 (mTouchState == TOUCH_STATE_SCROLLING)) { 1358 return true; 1359 } 1360 1361 switch (action & MotionEvent.ACTION_MASK) { 1362 case MotionEvent.ACTION_MOVE: { 1363 /* 1364 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check 1365 * whether the user has moved far enough from his original down touch. 1366 */ 1367 if (mActivePointerId != INVALID_POINTER) { 1368 determineScrollingStart(ev); 1369 } 1370 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN 1371 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN 1372 // i.e. fall through to the next case (don't break) 1373 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events 1374 // while it's small- this was causing a crash before we checked for INVALID_POINTER) 1375 break; 1376 } 1377 1378 case MotionEvent.ACTION_DOWN: { 1379 final float x = ev.getX(); 1380 final float y = ev.getY(); 1381 // Remember location of down touch 1382 mDownMotionX = x; 1383 mDownMotionY = y; 1384 mDownScrollX = getScrollX(); 1385 mLastMotionX = x; 1386 mLastMotionY = y; 1387 float[] p = mapPointFromViewToParent(this, x, y); 1388 mParentDownMotionX = p[0]; 1389 mParentDownMotionY = p[1]; 1390 mLastMotionXRemainder = 0; 1391 mTotalMotionX = 0; 1392 mActivePointerId = ev.getPointerId(0); 1393 1394 /* 1395 * If being flinged and user touches the screen, initiate drag; 1396 * otherwise don't. mScroller.isFinished should be false when 1397 * being flinged. 1398 */ 1399 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX()); 1400 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop); 1401 if (finishedScrolling) { 1402 mTouchState = TOUCH_STATE_REST; 1403 mScroller.abortAnimation(); 1404 } else { 1405 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) { 1406 mTouchState = TOUCH_STATE_SCROLLING; 1407 } else { 1408 mTouchState = TOUCH_STATE_REST; 1409 } 1410 } 1411 1412 // check if this can be the beginning of a tap on the side of the pages 1413 // to scroll the current page 1414 if (!DISABLE_TOUCH_SIDE_PAGES) { 1415 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) { 1416 if (getChildCount() > 0) { 1417 if (hitsPreviousPage(x, y)) { 1418 mTouchState = TOUCH_STATE_PREV_PAGE; 1419 } else if (hitsNextPage(x, y)) { 1420 mTouchState = TOUCH_STATE_NEXT_PAGE; 1421 } 1422 } 1423 } 1424 } 1425 break; 1426 } 1427 1428 case MotionEvent.ACTION_UP: 1429 case MotionEvent.ACTION_CANCEL: 1430 resetTouchState(); 1431 break; 1432 1433 case MotionEvent.ACTION_POINTER_UP: 1434 onSecondaryPointerUp(ev); 1435 releaseVelocityTracker(); 1436 break; 1437 } 1438 1439 /* 1440 * The only time we want to intercept motion events is if we are in the 1441 * drag mode. 1442 */ 1443 return mTouchState != TOUCH_STATE_REST; 1444 } 1445 1446 protected void determineScrollingStart(MotionEvent ev) { 1447 determineScrollingStart(ev, 1.0f); 1448 } 1449 1450 /* 1451 * Determines if we should change the touch state to start scrolling after the 1452 * user moves their touch point too far. 1453 */ 1454 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) { 1455 // Disallow scrolling if we don't have a valid pointer index 1456 final int pointerIndex = ev.findPointerIndex(mActivePointerId); 1457 if (pointerIndex == -1) return; 1458 1459 // Disallow scrolling if we started the gesture from outside the viewport 1460 final float x = ev.getX(pointerIndex); 1461 final float y = ev.getY(pointerIndex); 1462 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return; 1463 1464 final int xDiff = (int) Math.abs(x - mLastMotionX); 1465 final int yDiff = (int) Math.abs(y - mLastMotionY); 1466 1467 final int touchSlop = Math.round(touchSlopScale * mTouchSlop); 1468 boolean xPaged = xDiff > mPagingTouchSlop; 1469 boolean xMoved = xDiff > touchSlop; 1470 boolean yMoved = yDiff > touchSlop; 1471 1472 if (xMoved || xPaged || yMoved) { 1473 if (mUsePagingTouchSlop ? xPaged : xMoved) { 1474 // Scroll if the user moved far enough along the X axis 1475 mTouchState = TOUCH_STATE_SCROLLING; 1476 mTotalMotionX += Math.abs(mLastMotionX - x); 1477 mLastMotionX = x; 1478 mLastMotionXRemainder = 0; 1479 mTouchX = getViewportOffsetX() + getScrollX(); 1480 mSmoothingTime = System.nanoTime() / NANOTIME_DIV; 1481 pageBeginMoving(); 1482 } 1483 } 1484 } 1485 1486 protected float getMaxScrollProgress() { 1487 return 1.0f; 1488 } 1489 1490 protected void cancelCurrentPageLongPress() { 1491 if (mAllowLongPress) { 1492 //mAllowLongPress = false; 1493 // Try canceling the long press. It could also have been scheduled 1494 // by a distant descendant, so use the mAllowLongPress flag to block 1495 // everything 1496 final View currentPage = getPageAt(mCurrentPage); 1497 if (currentPage != null) { 1498 currentPage.cancelLongPress(); 1499 } 1500 } 1501 } 1502 1503 protected float getBoundedScrollProgress(int screenCenter, View v, int page) { 1504 final int halfScreenSize = getViewportWidth() / 2; 1505 1506 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter); 1507 screenCenter = Math.max(halfScreenSize, screenCenter); 1508 1509 return getScrollProgress(screenCenter, v, page); 1510 } 1511 1512 protected float getScrollProgress(int screenCenter, View v, int page) { 1513 final int halfScreenSize = getViewportWidth() / 2; 1514 1515 int totalDistance = v.getMeasuredWidth() + mPageSpacing; 1516 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize); 1517 1518 float scrollProgress = delta / (totalDistance * 1.0f); 1519 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress()); 1520 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress()); 1521 return scrollProgress; 1522 } 1523 1524 public int getScrollForPage(int index) { 1525 if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) { 1526 return 0; 1527 } else { 1528 return mPageScrolls[index]; 1529 } 1530 } 1531 1532 // While layout transitions are occurring, a child's position may stray from its baseline 1533 // position. This method returns the magnitude of this stray at any given time. 1534 public int getLayoutTransitionOffsetForPage(int index) { 1535 if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) { 1536 return 0; 1537 } else { 1538 View child = getChildAt(index); 1539 int scrollOffset = (getViewportWidth() - child.getMeasuredWidth()) / 2; 1540 int baselineX = mPageScrolls[index] + scrollOffset + getViewportOffsetX(); 1541 return (int) (child.getX() - baselineX); 1542 } 1543 } 1544 1545 // This curve determines how the effect of scrolling over the limits of the page dimishes 1546 // as the user pulls further and further from the bounds 1547 private float overScrollInfluenceCurve(float f) { 1548 f -= 1.0f; 1549 return f * f * f + 1.0f; 1550 } 1551 1552 protected void acceleratedOverScroll(float amount) { 1553 int screenSize = getViewportWidth(); 1554 1555 // We want to reach the max over scroll effect when the user has 1556 // over scrolled half the size of the screen 1557 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize); 1558 1559 if (f == 0) return; 1560 1561 // Clamp this factor, f, to -1 < f < 1 1562 if (Math.abs(f) >= 1) { 1563 f /= Math.abs(f); 1564 } 1565 1566 int overScrollAmount = (int) Math.round(f * screenSize); 1567 if (amount < 0) { 1568 mOverScrollX = overScrollAmount; 1569 super.scrollTo(0, getScrollY()); 1570 } else { 1571 mOverScrollX = mMaxScrollX + overScrollAmount; 1572 super.scrollTo(mMaxScrollX, getScrollY()); 1573 } 1574 invalidate(); 1575 } 1576 1577 protected void dampedOverScroll(float amount) { 1578 int screenSize = getViewportWidth(); 1579 1580 float f = (amount / screenSize); 1581 1582 if (f == 0) return; 1583 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f))); 1584 1585 // Clamp this factor, f, to -1 < f < 1 1586 if (Math.abs(f) >= 1) { 1587 f /= Math.abs(f); 1588 } 1589 1590 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize); 1591 if (amount < 0) { 1592 mOverScrollX = overScrollAmount; 1593 super.scrollTo(0, getScrollY()); 1594 } else { 1595 mOverScrollX = mMaxScrollX + overScrollAmount; 1596 super.scrollTo(mMaxScrollX, getScrollY()); 1597 } 1598 invalidate(); 1599 } 1600 1601 protected void overScroll(float amount) { 1602 dampedOverScroll(amount); 1603 } 1604 1605 protected float maxOverScroll() { 1606 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not 1607 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect 1608 float f = 1.0f; 1609 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f))); 1610 return OVERSCROLL_DAMP_FACTOR * f; 1611 } 1612 1613 protected void enableFreeScroll() { 1614 setEnableFreeScroll(true, -1); 1615 } 1616 1617 protected void disableFreeScroll(int snapPage) { 1618 setEnableFreeScroll(false, snapPage); 1619 } 1620 1621 void updateFreescrollBounds() { 1622 getOverviewModePages(mTempVisiblePagesRange); 1623 if (isLayoutRtl()) { 1624 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[1]); 1625 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[0]); 1626 } else { 1627 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]); 1628 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]); 1629 } 1630 } 1631 1632 private void setEnableFreeScroll(boolean freeScroll, int snapPage) { 1633 mFreeScroll = freeScroll; 1634 1635 if (snapPage == -1) { 1636 snapPage = getPageNearestToCenterOfScreen(); 1637 } 1638 1639 if (!mFreeScroll) { 1640 snapToPage(snapPage); 1641 } else { 1642 updateFreescrollBounds(); 1643 getOverviewModePages(mTempVisiblePagesRange); 1644 if (getCurrentPage() < mTempVisiblePagesRange[0]) { 1645 setCurrentPage(mTempVisiblePagesRange[0]); 1646 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) { 1647 setCurrentPage(mTempVisiblePagesRange[1]); 1648 } 1649 } 1650 1651 setEnableOverscroll(!freeScroll); 1652 } 1653 1654 private void setEnableOverscroll(boolean enable) { 1655 mAllowOverScroll = enable; 1656 } 1657 1658 int getNearestHoverOverPageIndex() { 1659 if (mDragView != null) { 1660 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2) 1661 + mDragView.getTranslationX()); 1662 getOverviewModePages(mTempVisiblePagesRange); 1663 int minDistance = Integer.MAX_VALUE; 1664 int minIndex = indexOfChild(mDragView); 1665 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) { 1666 View page = getPageAt(i); 1667 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2); 1668 int d = Math.abs(dragX - pageX); 1669 if (d < minDistance) { 1670 minIndex = i; 1671 minDistance = d; 1672 } 1673 } 1674 return minIndex; 1675 } 1676 return -1; 1677 } 1678 1679 @Override 1680 public boolean onTouchEvent(MotionEvent ev) { 1681 if (DISABLE_TOUCH_INTERACTION) { 1682 return false; 1683 } 1684 1685 super.onTouchEvent(ev); 1686 1687 // Skip touch handling if there are no pages to swipe 1688 if (getChildCount() <= 0) return super.onTouchEvent(ev); 1689 1690 acquireVelocityTrackerAndAddMovement(ev); 1691 1692 final int action = ev.getAction(); 1693 1694 switch (action & MotionEvent.ACTION_MASK) { 1695 case MotionEvent.ACTION_DOWN: 1696 /* 1697 * If being flinged and user touches, stop the fling. isFinished 1698 * will be false if being flinged. 1699 */ 1700 if (!mScroller.isFinished()) { 1701 mScroller.abortAnimation(); 1702 } 1703 1704 // Remember where the motion event started 1705 mDownMotionX = mLastMotionX = ev.getX(); 1706 mDownMotionY = mLastMotionY = ev.getY(); 1707 mDownScrollX = getScrollX(); 1708 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY); 1709 mParentDownMotionX = p[0]; 1710 mParentDownMotionY = p[1]; 1711 mLastMotionXRemainder = 0; 1712 mTotalMotionX = 0; 1713 mActivePointerId = ev.getPointerId(0); 1714 1715 if (mTouchState == TOUCH_STATE_SCROLLING) { 1716 pageBeginMoving(); 1717 } 1718 break; 1719 1720 case MotionEvent.ACTION_MOVE: 1721 if (mTouchState == TOUCH_STATE_SCROLLING) { 1722 // Scroll to follow the motion event 1723 final int pointerIndex = ev.findPointerIndex(mActivePointerId); 1724 1725 if (pointerIndex == -1) return true; 1726 1727 final float x = ev.getX(pointerIndex); 1728 final float deltaX = mLastMotionX + mLastMotionXRemainder - x; 1729 1730 mTotalMotionX += Math.abs(deltaX); 1731 1732 // Only scroll and update mLastMotionX if we have moved some discrete amount. We 1733 // keep the remainder because we are actually testing if we've moved from the last 1734 // scrolled position (which is discrete). 1735 if (Math.abs(deltaX) >= 1.0f) { 1736 mTouchX += deltaX; 1737 mSmoothingTime = System.nanoTime() / NANOTIME_DIV; 1738 if (!mDeferScrollUpdate) { 1739 scrollBy((int) deltaX, 0); 1740 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX); 1741 } else { 1742 invalidate(); 1743 } 1744 mLastMotionX = x; 1745 mLastMotionXRemainder = deltaX - (int) deltaX; 1746 } else { 1747 awakenScrollBars(); 1748 } 1749 } else if (mTouchState == TOUCH_STATE_REORDERING) { 1750 // Update the last motion position 1751 mLastMotionX = ev.getX(); 1752 mLastMotionY = ev.getY(); 1753 1754 // Update the parent down so that our zoom animations take this new movement into 1755 // account 1756 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY); 1757 mParentDownMotionX = pt[0]; 1758 mParentDownMotionY = pt[1]; 1759 updateDragViewTranslationDuringDrag(); 1760 1761 // Find the closest page to the touch point 1762 final int dragViewIndex = indexOfChild(mDragView); 1763 1764 // Change the drag view if we are hovering over the drop target 1765 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget( 1766 (int) mParentDownMotionX, (int) mParentDownMotionY); 1767 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete); 1768 1769 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX); 1770 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY); 1771 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX); 1772 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY); 1773 1774 final int pageUnderPointIndex = getNearestHoverOverPageIndex(); 1775 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) && 1776 !isHoveringOverDelete) { 1777 mTempVisiblePagesRange[0] = 0; 1778 mTempVisiblePagesRange[1] = getPageCount() - 1; 1779 getOverviewModePages(mTempVisiblePagesRange); 1780 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex && 1781 pageUnderPointIndex <= mTempVisiblePagesRange[1] && 1782 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) { 1783 mSidePageHoverIndex = pageUnderPointIndex; 1784 mSidePageHoverRunnable = new Runnable() { 1785 @Override 1786 public void run() { 1787 // Setup the scroll to the correct page before we swap the views 1788 snapToPage(pageUnderPointIndex); 1789 1790 // For each of the pages between the paged view and the drag view, 1791 // animate them from the previous position to the new position in 1792 // the layout (as a result of the drag view moving in the layout) 1793 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1; 1794 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ? 1795 dragViewIndex + 1 : pageUnderPointIndex; 1796 int upperIndex = (dragViewIndex > pageUnderPointIndex) ? 1797 dragViewIndex - 1 : pageUnderPointIndex; 1798 for (int i = lowerIndex; i <= upperIndex; ++i) { 1799 View v = getChildAt(i); 1800 // dragViewIndex < pageUnderPointIndex, so after we remove the 1801 // drag view all subsequent views to pageUnderPointIndex will 1802 // shift down. 1803 int oldX = getViewportOffsetX() + getChildOffset(i); 1804 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta); 1805 1806 // Animate the view translation from its old position to its new 1807 // position 1808 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY); 1809 if (anim != null) { 1810 anim.cancel(); 1811 } 1812 1813 v.setTranslationX(oldX - newX); 1814 anim = new AnimatorSet(); 1815 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION); 1816 anim.playTogether( 1817 ObjectAnimator.ofFloat(v, "translationX", 0f)); 1818 anim.start(); 1819 v.setTag(anim); 1820 } 1821 1822 removeView(mDragView); 1823 onRemoveView(mDragView, false); 1824 addView(mDragView, pageUnderPointIndex); 1825 onAddView(mDragView, pageUnderPointIndex); 1826 mSidePageHoverIndex = -1; 1827 mPageIndicator.setActiveMarker(getNextPage()); 1828 } 1829 }; 1830 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT); 1831 } 1832 } else { 1833 removeCallbacks(mSidePageHoverRunnable); 1834 mSidePageHoverIndex = -1; 1835 } 1836 } else { 1837 determineScrollingStart(ev); 1838 } 1839 break; 1840 1841 case MotionEvent.ACTION_UP: 1842 if (mTouchState == TOUCH_STATE_SCROLLING) { 1843 final int activePointerId = mActivePointerId; 1844 final int pointerIndex = ev.findPointerIndex(activePointerId); 1845 final float x = ev.getX(pointerIndex); 1846 final VelocityTracker velocityTracker = mVelocityTracker; 1847 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 1848 int velocityX = (int) velocityTracker.getXVelocity(activePointerId); 1849 final int deltaX = (int) (x - mDownMotionX); 1850 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth(); 1851 boolean isSignificantMove = Math.abs(deltaX) > pageWidth * 1852 SIGNIFICANT_MOVE_THRESHOLD; 1853 1854 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x); 1855 1856 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING && 1857 Math.abs(velocityX) > mFlingThresholdVelocity; 1858 1859 if (!mFreeScroll) { 1860 // In the case that the page is moved far to one direction and then is flung 1861 // in the opposite direction, we use a threshold to determine whether we should 1862 // just return to the starting page, or if we should skip one further. 1863 boolean returnToOriginalPage = false; 1864 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD && 1865 Math.signum(velocityX) != Math.signum(deltaX) && isFling) { 1866 returnToOriginalPage = true; 1867 } 1868 1869 int finalPage; 1870 // We give flings precedence over large moves, which is why we short-circuit our 1871 // test for a large move if a fling has been registered. That is, a large 1872 // move to the left and fling to the right will register as a fling to the right. 1873 final boolean isRtl = isLayoutRtl(); 1874 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0; 1875 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0; 1876 if (((isSignificantMove && !isDeltaXLeft && !isFling) || 1877 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) { 1878 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1; 1879 snapToPageWithVelocity(finalPage, velocityX); 1880 } else if (((isSignificantMove && isDeltaXLeft && !isFling) || 1881 (isFling && isVelocityXLeft)) && 1882 mCurrentPage < getChildCount() - 1) { 1883 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1; 1884 snapToPageWithVelocity(finalPage, velocityX); 1885 } else { 1886 snapToDestination(); 1887 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) { 1888 // at this point we have not moved beyond the touch slop 1889 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so 1890 // we can just page 1891 int nextPage = Math.max(0, mCurrentPage - 1); 1892 if (nextPage != mCurrentPage) { 1893 snapToPage(nextPage); 1894 } else { 1895 snapToDestination(); 1896 } 1897 } else { 1898 if (!mScroller.isFinished()) { 1899 mScroller.abortAnimation(); 1900 } 1901 1902 float scaleX = getScaleX(); 1903 int vX = (int) (-velocityX * scaleX); 1904 int initialScrollX = (int) (getScrollX() * scaleX); 1905 1906 mScroller.fling(initialScrollX, 1907 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0); 1908 invalidate(); 1909 } 1910 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) { 1911 // at this point we have not moved beyond the touch slop 1912 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so 1913 // we can just page 1914 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1); 1915 if (nextPage != mCurrentPage) { 1916 snapToPage(nextPage); 1917 } else { 1918 snapToDestination(); 1919 } 1920 } else if (mTouchState == TOUCH_STATE_REORDERING) { 1921 // Update the last motion position 1922 mLastMotionX = ev.getX(); 1923 mLastMotionY = ev.getY(); 1924 1925 // Update the parent down so that our zoom animations take this new movement into 1926 // account 1927 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY); 1928 mParentDownMotionX = pt[0]; 1929 mParentDownMotionY = pt[1]; 1930 updateDragViewTranslationDuringDrag(); 1931 boolean handledFling = false; 1932 if (!DISABLE_FLING_TO_DELETE) { 1933 // Check the velocity and see if we are flinging-to-delete 1934 PointF flingToDeleteVector = isFlingingToDelete(); 1935 if (flingToDeleteVector != null) { 1936 onFlingToDelete(flingToDeleteVector); 1937 handledFling = true; 1938 } 1939 } 1940 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX, 1941 (int) mParentDownMotionY)) { 1942 onDropToDelete(); 1943 } 1944 } else { 1945 if (!mCancelTap) { 1946 onUnhandledTap(ev); 1947 } 1948 } 1949 1950 // Remove the callback to wait for the side page hover timeout 1951 removeCallbacks(mSidePageHoverRunnable); 1952 // End any intermediate reordering states 1953 resetTouchState(); 1954 break; 1955 1956 case MotionEvent.ACTION_CANCEL: 1957 if (mTouchState == TOUCH_STATE_SCROLLING) { 1958 snapToDestination(); 1959 } 1960 resetTouchState(); 1961 break; 1962 1963 case MotionEvent.ACTION_POINTER_UP: 1964 onSecondaryPointerUp(ev); 1965 releaseVelocityTracker(); 1966 break; 1967 } 1968 1969 return true; 1970 } 1971 1972 public void onFlingToDelete(View v) {} 1973 public void onRemoveView(View v, boolean deletePermanently) {} 1974 public void onRemoveViewAnimationCompleted() {} 1975 public void onAddView(View v, int index) {} 1976 1977 private void resetTouchState() { 1978 releaseVelocityTracker(); 1979 endReordering(); 1980 mCancelTap = false; 1981 mTouchState = TOUCH_STATE_REST; 1982 mActivePointerId = INVALID_POINTER; 1983 } 1984 1985 protected void onUnhandledTap(MotionEvent ev) { 1986 ((Launcher) getContext()).onClick(this); 1987 } 1988 1989 @Override 1990 public boolean onGenericMotionEvent(MotionEvent event) { 1991 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 1992 switch (event.getAction()) { 1993 case MotionEvent.ACTION_SCROLL: { 1994 // Handle mouse (or ext. device) by shifting the page depending on the scroll 1995 final float vscroll; 1996 final float hscroll; 1997 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) { 1998 vscroll = 0; 1999 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL); 2000 } else { 2001 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL); 2002 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL); 2003 } 2004 if (hscroll != 0 || vscroll != 0) { 2005 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0) 2006 : (hscroll > 0 || vscroll > 0); 2007 if (isForwardScroll) { 2008 scrollRight(); 2009 } else { 2010 scrollLeft(); 2011 } 2012 return true; 2013 } 2014 } 2015 } 2016 } 2017 return super.onGenericMotionEvent(event); 2018 } 2019 2020 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) { 2021 if (mVelocityTracker == null) { 2022 mVelocityTracker = VelocityTracker.obtain(); 2023 } 2024 mVelocityTracker.addMovement(ev); 2025 } 2026 2027 private void releaseVelocityTracker() { 2028 if (mVelocityTracker != null) { 2029 mVelocityTracker.clear(); 2030 mVelocityTracker.recycle(); 2031 mVelocityTracker = null; 2032 } 2033 } 2034 2035 private void onSecondaryPointerUp(MotionEvent ev) { 2036 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> 2037 MotionEvent.ACTION_POINTER_INDEX_SHIFT; 2038 final int pointerId = ev.getPointerId(pointerIndex); 2039 if (pointerId == mActivePointerId) { 2040 // This was our active pointer going up. Choose a new 2041 // active pointer and adjust accordingly. 2042 // TODO: Make this decision more intelligent. 2043 final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 2044 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex); 2045 mLastMotionY = ev.getY(newPointerIndex); 2046 mLastMotionXRemainder = 0; 2047 mActivePointerId = ev.getPointerId(newPointerIndex); 2048 if (mVelocityTracker != null) { 2049 mVelocityTracker.clear(); 2050 } 2051 } 2052 } 2053 2054 @Override 2055 public void requestChildFocus(View child, View focused) { 2056 super.requestChildFocus(child, focused); 2057 int page = indexToPage(indexOfChild(child)); 2058 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) { 2059 snapToPage(page); 2060 } 2061 } 2062 2063 protected int getChildWidth(int index) { 2064 return getPageAt(index).getMeasuredWidth(); 2065 } 2066 2067 int getPageNearestToPoint(float x) { 2068 int index = 0; 2069 for (int i = 0; i < getChildCount(); ++i) { 2070 if (x < getChildAt(i).getRight() - getScrollX()) { 2071 return index; 2072 } else { 2073 index++; 2074 } 2075 } 2076 return Math.min(index, getChildCount() - 1); 2077 } 2078 2079 int getPageNearestToCenterOfScreen() { 2080 int minDistanceFromScreenCenter = Integer.MAX_VALUE; 2081 int minDistanceFromScreenCenterIndex = -1; 2082 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2); 2083 final int childCount = getChildCount(); 2084 for (int i = 0; i < childCount; ++i) { 2085 View layout = (View) getPageAt(i); 2086 int childWidth = layout.getMeasuredWidth(); 2087 int halfChildWidth = (childWidth / 2); 2088 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth; 2089 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter); 2090 if (distanceFromScreenCenter < minDistanceFromScreenCenter) { 2091 minDistanceFromScreenCenter = distanceFromScreenCenter; 2092 minDistanceFromScreenCenterIndex = i; 2093 } 2094 } 2095 return minDistanceFromScreenCenterIndex; 2096 } 2097 2098 protected void snapToDestination() { 2099 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION); 2100 } 2101 2102 private static class ScrollInterpolator implements Interpolator { 2103 public ScrollInterpolator() { 2104 } 2105 2106 public float getInterpolation(float t) { 2107 t -= 1.0f; 2108 return t*t*t*t*t + 1; 2109 } 2110 } 2111 2112 // We want the duration of the page snap animation to be influenced by the distance that 2113 // the screen has to travel, however, we don't want this duration to be effected in a 2114 // purely linear fashion. Instead, we use this method to moderate the effect that the distance 2115 // of travel has on the overall snap duration. 2116 float distanceInfluenceForSnapDuration(float f) { 2117 f -= 0.5f; // center the values about 0. 2118 f *= 0.3f * Math.PI / 2.0f; 2119 return (float) Math.sin(f); 2120 } 2121 2122 protected void snapToPageWithVelocity(int whichPage, int velocity) { 2123 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1)); 2124 int halfScreenSize = getViewportWidth() / 2; 2125 2126 final int newX = getScrollForPage(whichPage); 2127 int delta = newX - mUnboundedScrollX; 2128 int duration = 0; 2129 2130 if (Math.abs(velocity) < mMinFlingVelocity) { 2131 // If the velocity is low enough, then treat this more as an automatic page advance 2132 // as opposed to an apparent physical response to flinging 2133 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION); 2134 return; 2135 } 2136 2137 // Here we compute a "distance" that will be used in the computation of the overall 2138 // snap duration. This is a function of the actual distance that needs to be traveled; 2139 // we keep this value close to half screen size in order to reduce the variance in snap 2140 // duration as a function of the distance the page needs to travel. 2141 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize)); 2142 float distance = halfScreenSize + halfScreenSize * 2143 distanceInfluenceForSnapDuration(distanceRatio); 2144 2145 velocity = Math.abs(velocity); 2146 velocity = Math.max(mMinSnapVelocity, velocity); 2147 2148 // we want the page's snap velocity to approximately match the velocity at which the 2149 // user flings, so we scale the duration by a value near to the derivative of the scroll 2150 // interpolator at zero, ie. 5. We use 4 to make it a little slower. 2151 duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); 2152 2153 snapToPage(whichPage, delta, duration); 2154 } 2155 2156 protected void snapToPage(int whichPage) { 2157 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION); 2158 } 2159 2160 protected void snapToPageImmediately(int whichPage) { 2161 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true); 2162 } 2163 2164 protected void snapToPage(int whichPage, int duration) { 2165 snapToPage(whichPage, duration, false); 2166 } 2167 2168 protected void snapToPage(int whichPage, int duration, boolean immediate) { 2169 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1)); 2170 2171 int newX = getScrollForPage(whichPage); 2172 final int sX = mUnboundedScrollX; 2173 final int delta = newX - sX; 2174 snapToPage(whichPage, delta, duration, immediate); 2175 } 2176 2177 protected void snapToPage(int whichPage, int delta, int duration) { 2178 snapToPage(whichPage, delta, duration, false); 2179 } 2180 2181 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) { 2182 mNextPage = whichPage; 2183 View focusedChild = getFocusedChild(); 2184 if (focusedChild != null && whichPage != mCurrentPage && 2185 focusedChild == getPageAt(mCurrentPage)) { 2186 focusedChild.clearFocus(); 2187 } 2188 2189 sendScrollAccessibilityEvent(); 2190 2191 pageBeginMoving(); 2192 awakenScrollBars(duration); 2193 if (immediate) { 2194 duration = 0; 2195 } else if (duration == 0) { 2196 duration = Math.abs(delta); 2197 } 2198 2199 if (!mScroller.isFinished()) { 2200 mScroller.abortAnimation(); 2201 } 2202 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration); 2203 2204 notifyPageSwitchListener(); 2205 2206 // Trigger a compute() to finish switching pages if necessary 2207 if (immediate) { 2208 computeScroll(); 2209 } 2210 2211 // Defer loading associated pages until the scroll settles 2212 mDeferLoadAssociatedPagesUntilScrollCompletes = true; 2213 2214 mForceScreenScrolled = true; 2215 invalidate(); 2216 } 2217 2218 public void scrollLeft() { 2219 if (getNextPage() > 0) snapToPage(getNextPage() - 1); 2220 } 2221 2222 public void scrollRight() { 2223 if (getNextPage() < getChildCount() -1) snapToPage(getNextPage() + 1); 2224 } 2225 2226 public int getPageForView(View v) { 2227 int result = -1; 2228 if (v != null) { 2229 ViewParent vp = v.getParent(); 2230 int count = getChildCount(); 2231 for (int i = 0; i < count; i++) { 2232 if (vp == getPageAt(i)) { 2233 return i; 2234 } 2235 } 2236 } 2237 return result; 2238 } 2239 2240 /** 2241 * @return True is long presses are still allowed for the current touch 2242 */ 2243 public boolean allowLongPress() { 2244 return mAllowLongPress; 2245 } 2246 2247 @Override 2248 public boolean performLongClick() { 2249 mCancelTap = true; 2250 return super.performLongClick(); 2251 } 2252 2253 /** 2254 * Set true to allow long-press events to be triggered, usually checked by 2255 * {@link Launcher} to accept or block dpad-initiated long-presses. 2256 */ 2257 public void setAllowLongPress(boolean allowLongPress) { 2258 mAllowLongPress = allowLongPress; 2259 } 2260 2261 public static class SavedState extends BaseSavedState { 2262 int currentPage = -1; 2263 2264 SavedState(Parcelable superState) { 2265 super(superState); 2266 } 2267 2268 private SavedState(Parcel in) { 2269 super(in); 2270 currentPage = in.readInt(); 2271 } 2272 2273 @Override 2274 public void writeToParcel(Parcel out, int flags) { 2275 super.writeToParcel(out, flags); 2276 out.writeInt(currentPage); 2277 } 2278 2279 public static final Parcelable.Creator<SavedState> CREATOR = 2280 new Parcelable.Creator<SavedState>() { 2281 public SavedState createFromParcel(Parcel in) { 2282 return new SavedState(in); 2283 } 2284 2285 public SavedState[] newArray(int size) { 2286 return new SavedState[size]; 2287 } 2288 }; 2289 } 2290 2291 protected void loadAssociatedPages(int page) { 2292 loadAssociatedPages(page, false); 2293 } 2294 protected void loadAssociatedPages(int page, boolean immediateAndOnly) { 2295 if (mContentIsRefreshable) { 2296 final int count = getChildCount(); 2297 if (page < count) { 2298 int lowerPageBound = getAssociatedLowerPageBound(page); 2299 int upperPageBound = getAssociatedUpperPageBound(page); 2300 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/" 2301 + upperPageBound); 2302 // First, clear any pages that should no longer be loaded 2303 for (int i = 0; i < count; ++i) { 2304 Page layout = (Page) getPageAt(i); 2305 if ((i < lowerPageBound) || (i > upperPageBound)) { 2306 if (layout.getPageChildCount() > 0) { 2307 layout.removeAllViewsOnPage(); 2308 } 2309 mDirtyPageContent.set(i, true); 2310 } 2311 } 2312 // Next, load any new pages 2313 for (int i = 0; i < count; ++i) { 2314 if ((i != page) && immediateAndOnly) { 2315 continue; 2316 } 2317 if (lowerPageBound <= i && i <= upperPageBound) { 2318 if (mDirtyPageContent.get(i)) { 2319 syncPageItems(i, (i == page) && immediateAndOnly); 2320 mDirtyPageContent.set(i, false); 2321 } 2322 } 2323 } 2324 } 2325 } 2326 } 2327 2328 protected int getAssociatedLowerPageBound(int page) { 2329 return Math.max(0, page - 1); 2330 } 2331 protected int getAssociatedUpperPageBound(int page) { 2332 final int count = getChildCount(); 2333 return Math.min(page + 1, count - 1); 2334 } 2335 2336 /** 2337 * This method is called ONLY to synchronize the number of pages that the paged view has. 2338 * To actually fill the pages with information, implement syncPageItems() below. It is 2339 * guaranteed that syncPageItems() will be called for a particular page before it is shown, 2340 * and therefore, individual page items do not need to be updated in this method. 2341 */ 2342 public abstract void syncPages(); 2343 2344 /** 2345 * This method is called to synchronize the items that are on a particular page. If views on 2346 * the page can be reused, then they should be updated within this method. 2347 */ 2348 public abstract void syncPageItems(int page, boolean immediate); 2349 2350 protected void invalidatePageData() { 2351 invalidatePageData(-1, false); 2352 } 2353 protected void invalidatePageData(int currentPage) { 2354 invalidatePageData(currentPage, false); 2355 } 2356 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) { 2357 if (!mIsDataReady) { 2358 return; 2359 } 2360 2361 if (mContentIsRefreshable) { 2362 // Force all scrolling-related behavior to end 2363 mScroller.forceFinished(true); 2364 mNextPage = INVALID_PAGE; 2365 2366 // Update all the pages 2367 syncPages(); 2368 2369 // We must force a measure after we've loaded the pages to update the content width and 2370 // to determine the full scroll width 2371 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY), 2372 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY)); 2373 2374 // Set a new page as the current page if necessary 2375 if (currentPage > -1) { 2376 setCurrentPage(Math.min(getPageCount() - 1, currentPage)); 2377 } 2378 2379 // Mark each of the pages as dirty 2380 final int count = getChildCount(); 2381 mDirtyPageContent.clear(); 2382 for (int i = 0; i < count; ++i) { 2383 mDirtyPageContent.add(true); 2384 } 2385 2386 // Load any pages that are necessary for the current window of views 2387 loadAssociatedPages(mCurrentPage, immediateAndOnly); 2388 requestLayout(); 2389 } 2390 if (isPageMoving()) { 2391 // If the page is moving, then snap it to the final position to ensure we don't get 2392 // stuck between pages 2393 snapToDestination(); 2394 } 2395 } 2396 2397 // Animate the drag view back to the original position 2398 void animateDragViewToOriginalPosition() { 2399 if (mDragView != null) { 2400 AnimatorSet anim = new AnimatorSet(); 2401 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION); 2402 anim.playTogether( 2403 ObjectAnimator.ofFloat(mDragView, "translationX", 0f), 2404 ObjectAnimator.ofFloat(mDragView, "translationY", 0f), 2405 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f), 2406 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f)); 2407 anim.addListener(new AnimatorListenerAdapter() { 2408 @Override 2409 public void onAnimationEnd(Animator animation) { 2410 onPostReorderingAnimationCompleted(); 2411 } 2412 }); 2413 anim.start(); 2414 } 2415 } 2416 2417 protected void onStartReordering() { 2418 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.) 2419 mTouchState = TOUCH_STATE_REORDERING; 2420 mIsReordering = true; 2421 2422 // We must invalidate to trigger a redraw to update the layers such that the drag view 2423 // is always drawn on top 2424 invalidate(); 2425 } 2426 2427 private void onPostReorderingAnimationCompleted() { 2428 // Trigger the callback when reordering has settled 2429 --mPostReorderingPreZoomInRemainingAnimationCount; 2430 if (mPostReorderingPreZoomInRunnable != null && 2431 mPostReorderingPreZoomInRemainingAnimationCount == 0) { 2432 mPostReorderingPreZoomInRunnable.run(); 2433 mPostReorderingPreZoomInRunnable = null; 2434 } 2435 } 2436 2437 protected void onEndReordering() { 2438 mIsReordering = false; 2439 } 2440 2441 public boolean startReordering(View v) { 2442 int dragViewIndex = indexOfChild(v); 2443 2444 if (mTouchState != TOUCH_STATE_REST) return false; 2445 2446 mTempVisiblePagesRange[0] = 0; 2447 mTempVisiblePagesRange[1] = getPageCount() - 1; 2448 getOverviewModePages(mTempVisiblePagesRange); 2449 mReorderingStarted = true; 2450 2451 // Check if we are within the reordering range 2452 if (mTempVisiblePagesRange[0] <= dragViewIndex && 2453 dragViewIndex <= mTempVisiblePagesRange[1]) { 2454 // Find the drag view under the pointer 2455 mDragView = getChildAt(dragViewIndex); 2456 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start(); 2457 mDragViewBaselineLeft = mDragView.getLeft(); 2458 disableFreeScroll(-1); 2459 onStartReordering(); 2460 return true; 2461 } 2462 return false; 2463 } 2464 2465 boolean isReordering(boolean testTouchState) { 2466 boolean state = mIsReordering; 2467 if (testTouchState) { 2468 state &= (mTouchState == TOUCH_STATE_REORDERING); 2469 } 2470 return state; 2471 } 2472 void endReordering() { 2473 // For simplicity, we call endReordering sometimes even if reordering was never started. 2474 // In that case, we don't want to do anything. 2475 if (!mReorderingStarted) return; 2476 mReorderingStarted = false; 2477 2478 // If we haven't flung-to-delete the current child, then we just animate the drag view 2479 // back into position 2480 final Runnable onCompleteRunnable = new Runnable() { 2481 @Override 2482 public void run() { 2483 onEndReordering(); 2484 } 2485 }; 2486 if (!mDeferringForDelete) { 2487 mPostReorderingPreZoomInRunnable = new Runnable() { 2488 public void run() { 2489 onCompleteRunnable.run(); 2490 enableFreeScroll(); 2491 }; 2492 }; 2493 2494 mPostReorderingPreZoomInRemainingAnimationCount = 2495 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT; 2496 // Snap to the current page 2497 snapToPage(indexOfChild(mDragView), 0); 2498 // Animate the drag view back to the front position 2499 animateDragViewToOriginalPosition(); 2500 } else { 2501 // Handled in post-delete-animation-callbacks 2502 } 2503 } 2504 2505 /* 2506 * Flinging to delete - IN PROGRESS 2507 */ 2508 private PointF isFlingingToDelete() { 2509 ViewConfiguration config = ViewConfiguration.get(getContext()); 2510 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity()); 2511 2512 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) { 2513 // Do a quick dot product test to ensure that we are flinging upwards 2514 PointF vel = new PointF(mVelocityTracker.getXVelocity(), 2515 mVelocityTracker.getYVelocity()); 2516 PointF upVec = new PointF(0f, -1f); 2517 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) / 2518 (vel.length() * upVec.length())); 2519 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) { 2520 return vel; 2521 } 2522 } 2523 return null; 2524 } 2525 2526 /** 2527 * Creates an animation from the current drag view along its current velocity vector. 2528 * For this animation, the alpha runs for a fixed duration and we update the position 2529 * progressively. 2530 */ 2531 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener { 2532 private View mDragView; 2533 private PointF mVelocity; 2534 private Rect mFrom; 2535 private long mPrevTime; 2536 private float mFriction; 2537 2538 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f); 2539 2540 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from, 2541 long startTime, float friction) { 2542 mDragView = dragView; 2543 mVelocity = vel; 2544 mFrom = from; 2545 mPrevTime = startTime; 2546 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction); 2547 } 2548 2549 @Override 2550 public void onAnimationUpdate(ValueAnimator animation) { 2551 float t = ((Float) animation.getAnimatedValue()).floatValue(); 2552 long curTime = AnimationUtils.currentAnimationTimeMillis(); 2553 2554 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f); 2555 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f); 2556 2557 mDragView.setTranslationX(mFrom.left); 2558 mDragView.setTranslationY(mFrom.top); 2559 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t)); 2560 2561 mVelocity.x *= mFriction; 2562 mVelocity.y *= mFriction; 2563 mPrevTime = curTime; 2564 } 2565 }; 2566 2567 private static final int ANIM_TAG_KEY = 100; 2568 2569 private Runnable createPostDeleteAnimationRunnable(final View dragView) { 2570 return new Runnable() { 2571 @Override 2572 public void run() { 2573 int dragViewIndex = indexOfChild(dragView); 2574 2575 // For each of the pages around the drag view, animate them from the previous 2576 // position to the new position in the layout (as a result of the drag view moving 2577 // in the layout) 2578 // NOTE: We can make an assumption here because we have side-bound pages that we 2579 // will always have pages to animate in from the left 2580 getOverviewModePages(mTempVisiblePagesRange); 2581 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]); 2582 boolean slideFromLeft = (isLastWidgetPage || 2583 dragViewIndex > mTempVisiblePagesRange[0]); 2584 2585 // Setup the scroll to the correct page before we swap the views 2586 if (slideFromLeft) { 2587 snapToPageImmediately(dragViewIndex - 1); 2588 } 2589 2590 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]); 2591 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1); 2592 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 ); 2593 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex); 2594 ArrayList<Animator> animations = new ArrayList<Animator>(); 2595 for (int i = lowerIndex; i <= upperIndex; ++i) { 2596 View v = getChildAt(i); 2597 // dragViewIndex < pageUnderPointIndex, so after we remove the 2598 // drag view all subsequent views to pageUnderPointIndex will 2599 // shift down. 2600 int oldX = 0; 2601 int newX = 0; 2602 if (slideFromLeft) { 2603 if (i == 0) { 2604 // Simulate the page being offscreen with the page spacing 2605 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i) 2606 - mPageSpacing; 2607 } else { 2608 oldX = getViewportOffsetX() + getChildOffset(i - 1); 2609 } 2610 newX = getViewportOffsetX() + getChildOffset(i); 2611 } else { 2612 oldX = getChildOffset(i) - getChildOffset(i - 1); 2613 newX = 0; 2614 } 2615 2616 // Animate the view translation from its old position to its new 2617 // position 2618 AnimatorSet anim = (AnimatorSet) v.getTag(); 2619 if (anim != null) { 2620 anim.cancel(); 2621 } 2622 2623 // Note: Hacky, but we want to skip any optimizations to not draw completely 2624 // hidden views 2625 v.setAlpha(Math.max(v.getAlpha(), 0.01f)); 2626 v.setTranslationX(oldX - newX); 2627 anim = new AnimatorSet(); 2628 anim.playTogether( 2629 ObjectAnimator.ofFloat(v, "translationX", 0f), 2630 ObjectAnimator.ofFloat(v, "alpha", 1f)); 2631 animations.add(anim); 2632 v.setTag(ANIM_TAG_KEY, anim); 2633 } 2634 2635 AnimatorSet slideAnimations = new AnimatorSet(); 2636 slideAnimations.playTogether(animations); 2637 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION); 2638 slideAnimations.addListener(new AnimatorListenerAdapter() { 2639 @Override 2640 public void onAnimationEnd(Animator animation) { 2641 mDeferringForDelete = false; 2642 onEndReordering(); 2643 onRemoveViewAnimationCompleted(); 2644 } 2645 }); 2646 slideAnimations.start(); 2647 2648 removeView(dragView); 2649 onRemoveView(dragView, true); 2650 } 2651 }; 2652 } 2653 2654 public void onFlingToDelete(PointF vel) { 2655 final long startTime = AnimationUtils.currentAnimationTimeMillis(); 2656 2657 // NOTE: Because it takes time for the first frame of animation to actually be 2658 // called and we expect the animation to be a continuation of the fling, we have 2659 // to account for the time that has elapsed since the fling finished. And since 2660 // we don't have a startDelay, we will always get call to update when we call 2661 // start() (which we want to ignore). 2662 final TimeInterpolator tInterpolator = new TimeInterpolator() { 2663 private int mCount = -1; 2664 private long mStartTime; 2665 private float mOffset; 2666 /* Anonymous inner class ctor */ { 2667 mStartTime = startTime; 2668 } 2669 2670 @Override 2671 public float getInterpolation(float t) { 2672 if (mCount < 0) { 2673 mCount++; 2674 } else if (mCount == 0) { 2675 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() - 2676 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION); 2677 mCount++; 2678 } 2679 return Math.min(1f, mOffset + t); 2680 } 2681 }; 2682 2683 final Rect from = new Rect(); 2684 final View dragView = mDragView; 2685 from.left = (int) dragView.getTranslationX(); 2686 from.top = (int) dragView.getTranslationY(); 2687 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel, 2688 from, startTime, FLING_TO_DELETE_FRICTION); 2689 2690 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView); 2691 2692 // Create and start the animation 2693 ValueAnimator mDropAnim = new ValueAnimator(); 2694 mDropAnim.setInterpolator(tInterpolator); 2695 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION); 2696 mDropAnim.setFloatValues(0f, 1f); 2697 mDropAnim.addUpdateListener(updateCb); 2698 mDropAnim.addListener(new AnimatorListenerAdapter() { 2699 public void onAnimationEnd(Animator animation) { 2700 onAnimationEndRunnable.run(); 2701 } 2702 }); 2703 mDropAnim.start(); 2704 mDeferringForDelete = true; 2705 } 2706 2707 /* Drag to delete */ 2708 private boolean isHoveringOverDeleteDropTarget(int x, int y) { 2709 if (mDeleteDropTarget != null) { 2710 mAltTmpRect.set(0, 0, 0, 0); 2711 View parent = (View) mDeleteDropTarget.getParent(); 2712 if (parent != null) { 2713 parent.getGlobalVisibleRect(mAltTmpRect); 2714 } 2715 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect); 2716 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top); 2717 return mTmpRect.contains(x, y); 2718 } 2719 return false; 2720 } 2721 2722 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {} 2723 2724 private void onDropToDelete() { 2725 final View dragView = mDragView; 2726 2727 final float toScale = 0f; 2728 final float toAlpha = 0f; 2729 2730 // Create and start the complex animation 2731 ArrayList<Animator> animations = new ArrayList<Animator>(); 2732 AnimatorSet motionAnim = new AnimatorSet(); 2733 motionAnim.setInterpolator(new DecelerateInterpolator(2)); 2734 motionAnim.playTogether( 2735 ObjectAnimator.ofFloat(dragView, "scaleX", toScale), 2736 ObjectAnimator.ofFloat(dragView, "scaleY", toScale)); 2737 animations.add(motionAnim); 2738 2739 AnimatorSet alphaAnim = new AnimatorSet(); 2740 alphaAnim.setInterpolator(new LinearInterpolator()); 2741 alphaAnim.playTogether( 2742 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha)); 2743 animations.add(alphaAnim); 2744 2745 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView); 2746 2747 AnimatorSet anim = new AnimatorSet(); 2748 anim.playTogether(animations); 2749 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION); 2750 anim.addListener(new AnimatorListenerAdapter() { 2751 public void onAnimationEnd(Animator animation) { 2752 onAnimationEndRunnable.run(); 2753 } 2754 }); 2755 anim.start(); 2756 2757 mDeferringForDelete = true; 2758 } 2759 2760 /* Accessibility */ 2761 @Override 2762 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 2763 super.onInitializeAccessibilityNodeInfo(info); 2764 info.setScrollable(getPageCount() > 1); 2765 if (getCurrentPage() < getPageCount() - 1) { 2766 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); 2767 } 2768 if (getCurrentPage() > 0) { 2769 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); 2770 } 2771 } 2772 2773 @Override 2774 public void sendAccessibilityEvent(int eventType) { 2775 // Don't let the view send real scroll events. 2776 if (eventType != AccessibilityEvent.TYPE_VIEW_SCROLLED) { 2777 super.sendAccessibilityEvent(eventType); 2778 } 2779 } 2780 2781 @Override 2782 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 2783 super.onInitializeAccessibilityEvent(event); 2784 event.setScrollable(true); 2785 } 2786 2787 @Override 2788 public boolean performAccessibilityAction(int action, Bundle arguments) { 2789 if (super.performAccessibilityAction(action, arguments)) { 2790 return true; 2791 } 2792 switch (action) { 2793 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: { 2794 if (getCurrentPage() < getPageCount() - 1) { 2795 scrollRight(); 2796 return true; 2797 } 2798 } break; 2799 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: { 2800 if (getCurrentPage() > 0) { 2801 scrollLeft(); 2802 return true; 2803 } 2804 } break; 2805 } 2806 return false; 2807 } 2808 2809 protected String getCurrentPageDescription() { 2810 return String.format(getContext().getString(R.string.default_scroll_format), 2811 getNextPage() + 1, getChildCount()); 2812 } 2813 2814 @Override 2815 public boolean onHoverEvent(android.view.MotionEvent event) { 2816 return true; 2817 } 2818 } 2819