1 /* 2 * Copyright (C) 2010 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.launcher2; 18 19 import android.animation.Animator; 20 import android.animation.AnimatorInflater; 21 import android.animation.AnimatorListenerAdapter; 22 import android.animation.ObjectAnimator; 23 import android.animation.ValueAnimator; 24 import android.content.Context; 25 import android.content.res.TypedArray; 26 import android.graphics.Canvas; 27 import android.graphics.Rect; 28 import android.os.Parcel; 29 import android.os.Parcelable; 30 import android.util.AttributeSet; 31 import android.util.Log; 32 import android.view.ActionMode; 33 import android.view.InputDevice; 34 import android.view.KeyEvent; 35 import android.view.MotionEvent; 36 import android.view.VelocityTracker; 37 import android.view.View; 38 import android.view.ViewConfiguration; 39 import android.view.ViewGroup; 40 import android.view.ViewParent; 41 import android.view.accessibility.AccessibilityEvent; 42 import android.view.accessibility.AccessibilityManager; 43 import android.view.accessibility.AccessibilityNodeInfo; 44 import android.view.animation.Interpolator; 45 import android.widget.Checkable; 46 import android.widget.ImageView; 47 import android.widget.Scroller; 48 49 import com.android.launcher.R; 50 51 import java.util.ArrayList; 52 53 /** 54 * An abstraction of the original Workspace which supports browsing through a 55 * sequential list of "pages" 56 */ 57 public abstract class PagedView extends ViewGroup { 58 private static final String TAG = "PagedView"; 59 private static final boolean DEBUG = false; 60 protected static final int INVALID_PAGE = -1; 61 62 // the min drag distance for a fling to register, to prevent random page shifts 63 private static final int MIN_LENGTH_FOR_FLING = 25; 64 // The min drag distance to trigger a page shift (regardless of velocity) 65 private static final int MIN_LENGTH_FOR_MOVE = 200; 66 67 private static final int PAGE_SNAP_ANIMATION_DURATION = 550; 68 protected static final float NANOTIME_DIV = 1000000000.0f; 69 70 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2; 71 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f; 72 private static final int MINIMUM_SNAP_VELOCITY = 2200; 73 private static final int MIN_FLING_VELOCITY = 250; 74 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f; 75 76 // the velocity at which a fling gesture will cause us to snap to the next page 77 protected int mSnapVelocity = 500; 78 79 protected float mDensity; 80 protected float mSmoothingTime; 81 protected float mTouchX; 82 83 protected boolean mFirstLayout = true; 84 85 protected int mCurrentPage; 86 protected int mNextPage = INVALID_PAGE; 87 protected int mMaxScrollX; 88 protected Scroller mScroller; 89 private VelocityTracker mVelocityTracker; 90 91 private float mDownMotionX; 92 protected float mLastMotionX; 93 protected float mLastMotionXRemainder; 94 protected float mLastMotionY; 95 protected float mTotalMotionX; 96 private int mLastScreenCenter = -1; 97 98 protected final static int TOUCH_STATE_REST = 0; 99 protected final static int TOUCH_STATE_SCROLLING = 1; 100 protected final static int TOUCH_STATE_PREV_PAGE = 2; 101 protected final static int TOUCH_STATE_NEXT_PAGE = 3; 102 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f; 103 104 protected int mTouchState = TOUCH_STATE_REST; 105 106 protected OnLongClickListener mLongClickListener; 107 108 protected boolean mAllowLongPress = true; 109 110 protected int mTouchSlop; 111 private int mPagingTouchSlop; 112 private int mMaximumVelocity; 113 private int mMinimumWidth; 114 protected int mPageSpacing; 115 protected int mPageLayoutPaddingTop; 116 protected int mPageLayoutPaddingBottom; 117 protected int mPageLayoutPaddingLeft; 118 protected int mPageLayoutPaddingRight; 119 protected int mPageLayoutWidthGap; 120 protected int mPageLayoutHeightGap; 121 protected int mCellCountX = 0; 122 protected int mCellCountY = 0; 123 protected boolean mCenterPagesVertically; 124 protected boolean mAllowOverScroll = true; 125 protected int mUnboundedScrollX; 126 127 // parameter that adjusts the layout to be optimized for pages with that scale factor 128 protected float mLayoutScale = 1.0f; 129 130 protected static final int INVALID_POINTER = -1; 131 132 protected int mActivePointerId = INVALID_POINTER; 133 134 private PageSwitchListener mPageSwitchListener; 135 136 private ArrayList<Boolean> mDirtyPageContent; 137 private boolean mDirtyPageAlpha = true; 138 139 // choice modes 140 protected static final int CHOICE_MODE_NONE = 0; 141 protected static final int CHOICE_MODE_SINGLE = 1; 142 // Multiple selection mode is not supported by all Launcher actions atm 143 protected static final int CHOICE_MODE_MULTIPLE = 2; 144 145 protected int mChoiceMode; 146 private ActionMode mActionMode; 147 148 // If true, syncPages and syncPageItems will be called to refresh pages 149 protected boolean mContentIsRefreshable = true; 150 151 // If true, modify alpha of neighboring pages as user scrolls left/right 152 protected boolean mFadeInAdjacentScreens = true; 153 154 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding 155 // to switch to a new page 156 protected boolean mUsePagingTouchSlop = true; 157 158 // If true, the subclass should directly update mScrollX itself in its computeScroll method 159 // (SmoothPagedView does this) 160 protected boolean mDeferScrollUpdate = false; 161 162 protected boolean mIsPageMoving = false; 163 164 // All syncs and layout passes are deferred until data is ready. 165 protected boolean mIsDataReady = false; 166 167 // Scrolling indicator 168 private ValueAnimator mScrollIndicatorAnimator; 169 private ImageView mScrollIndicator; 170 private int mScrollIndicatorPaddingLeft; 171 private int mScrollIndicatorPaddingRight; 172 private boolean mHasScrollIndicator = true; 173 protected static final int sScrollIndicatorFadeInDuration = 150; 174 protected static final int sScrollIndicatorFadeOutDuration = 650; 175 protected static final int sScrollIndicatorFlashDuration = 650; 176 177 // If set, will defer loading associated pages until the scrolling settles 178 private boolean mDeferLoadAssociatedPagesUntilScrollCompletes; 179 180 public interface PageSwitchListener { 181 void onPageSwitch(View newPage, int newPageIndex); 182 } 183 184 public PagedView(Context context) { 185 this(context, null); 186 } 187 188 public PagedView(Context context, AttributeSet attrs) { 189 this(context, attrs, 0); 190 } 191 192 public PagedView(Context context, AttributeSet attrs, int defStyle) { 193 super(context, attrs, defStyle); 194 mChoiceMode = CHOICE_MODE_NONE; 195 196 TypedArray a = context.obtainStyledAttributes(attrs, 197 R.styleable.PagedView, defStyle, 0); 198 mPageSpacing = a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0); 199 mPageLayoutPaddingTop = a.getDimensionPixelSize( 200 R.styleable.PagedView_pageLayoutPaddingTop, 0); 201 mPageLayoutPaddingBottom = a.getDimensionPixelSize( 202 R.styleable.PagedView_pageLayoutPaddingBottom, 0); 203 mPageLayoutPaddingLeft = a.getDimensionPixelSize( 204 R.styleable.PagedView_pageLayoutPaddingLeft, 0); 205 mPageLayoutPaddingRight = a.getDimensionPixelSize( 206 R.styleable.PagedView_pageLayoutPaddingRight, 0); 207 mPageLayoutWidthGap = a.getDimensionPixelSize( 208 R.styleable.PagedView_pageLayoutWidthGap, 0); 209 mPageLayoutHeightGap = a.getDimensionPixelSize( 210 R.styleable.PagedView_pageLayoutHeightGap, 0); 211 mScrollIndicatorPaddingLeft = 212 a.getDimensionPixelSize(R.styleable.PagedView_scrollIndicatorPaddingLeft, 0); 213 mScrollIndicatorPaddingRight = 214 a.getDimensionPixelSize(R.styleable.PagedView_scrollIndicatorPaddingRight, 0); 215 a.recycle(); 216 217 setHapticFeedbackEnabled(false); 218 init(); 219 } 220 221 /** 222 * Initializes various states for this workspace. 223 */ 224 protected void init() { 225 mDirtyPageContent = new ArrayList<Boolean>(); 226 mDirtyPageContent.ensureCapacity(32); 227 mScroller = new Scroller(getContext(), new ScrollInterpolator()); 228 mCurrentPage = 0; 229 mCenterPagesVertically = true; 230 231 final ViewConfiguration configuration = ViewConfiguration.get(getContext()); 232 mTouchSlop = configuration.getScaledTouchSlop(); 233 mPagingTouchSlop = configuration.getScaledPagingTouchSlop(); 234 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); 235 mDensity = getResources().getDisplayMetrics().density; 236 } 237 238 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) { 239 mPageSwitchListener = pageSwitchListener; 240 if (mPageSwitchListener != null) { 241 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage); 242 } 243 } 244 245 /** 246 * Called by subclasses to mark that data is ready, and that we can begin loading and laying 247 * out pages. 248 */ 249 protected void setDataIsReady() { 250 mIsDataReady = true; 251 } 252 protected boolean isDataReady() { 253 return mIsDataReady; 254 } 255 256 /** 257 * Returns the index of the currently displayed page. 258 * 259 * @return The index of the currently displayed page. 260 */ 261 int getCurrentPage() { 262 return mCurrentPage; 263 } 264 265 int getPageCount() { 266 return getChildCount(); 267 } 268 269 View getPageAt(int index) { 270 return getChildAt(index); 271 } 272 273 protected int indexToPage(int index) { 274 return index; 275 } 276 277 /** 278 * Updates the scroll of the current page immediately to its final scroll position. We use this 279 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of 280 * the previous tab page. 281 */ 282 protected void updateCurrentPageScroll() { 283 int newX = getChildOffset(mCurrentPage) - getRelativeChildOffset(mCurrentPage); 284 scrollTo(newX, 0); 285 mScroller.setFinalX(newX); 286 } 287 288 /** 289 * Sets the current page. 290 */ 291 void setCurrentPage(int currentPage) { 292 if (!mScroller.isFinished()) { 293 mScroller.abortAnimation(); 294 } 295 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the 296 // the default 297 if (getChildCount() == 0) { 298 return; 299 } 300 301 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1)); 302 updateCurrentPageScroll(); 303 updateScrollingIndicator(); 304 notifyPageSwitchListener(); 305 invalidate(); 306 } 307 308 protected void notifyPageSwitchListener() { 309 if (mPageSwitchListener != null) { 310 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage); 311 } 312 } 313 314 protected void pageBeginMoving() { 315 if (!mIsPageMoving) { 316 mIsPageMoving = true; 317 onPageBeginMoving(); 318 } 319 } 320 321 protected void pageEndMoving() { 322 if (mIsPageMoving) { 323 mIsPageMoving = false; 324 onPageEndMoving(); 325 } 326 } 327 328 protected boolean isPageMoving() { 329 return mIsPageMoving; 330 } 331 332 // a method that subclasses can override to add behavior 333 protected void onPageBeginMoving() { 334 showScrollingIndicator(false); 335 } 336 337 // a method that subclasses can override to add behavior 338 protected void onPageEndMoving() { 339 hideScrollingIndicator(false); 340 } 341 342 /** 343 * Registers the specified listener on each page contained in this workspace. 344 * 345 * @param l The listener used to respond to long clicks. 346 */ 347 @Override 348 public void setOnLongClickListener(OnLongClickListener l) { 349 mLongClickListener = l; 350 final int count = getPageCount(); 351 for (int i = 0; i < count; i++) { 352 getPageAt(i).setOnLongClickListener(l); 353 } 354 } 355 356 @Override 357 public void scrollBy(int x, int y) { 358 scrollTo(mUnboundedScrollX + x, mScrollY + y); 359 } 360 361 @Override 362 public void scrollTo(int x, int y) { 363 mUnboundedScrollX = x; 364 365 if (x < 0) { 366 super.scrollTo(0, y); 367 if (mAllowOverScroll) { 368 overScroll(x); 369 } 370 } else if (x > mMaxScrollX) { 371 super.scrollTo(mMaxScrollX, y); 372 if (mAllowOverScroll) { 373 overScroll(x - mMaxScrollX); 374 } 375 } else { 376 super.scrollTo(x, y); 377 } 378 379 mTouchX = x; 380 mSmoothingTime = System.nanoTime() / NANOTIME_DIV; 381 } 382 383 // we moved this functionality to a helper function so SmoothPagedView can reuse it 384 protected boolean computeScrollHelper() { 385 if (mScroller.computeScrollOffset()) { 386 // Don't bother scrolling if the page does not need to be moved 387 if (mScrollX != mScroller.getCurrX() || mScrollY != mScroller.getCurrY()) { 388 mDirtyPageAlpha = true; 389 scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); 390 } 391 invalidate(); 392 return true; 393 } else if (mNextPage != INVALID_PAGE) { 394 mDirtyPageAlpha = true; 395 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1)); 396 mNextPage = INVALID_PAGE; 397 notifyPageSwitchListener(); 398 399 // Load the associated pages if necessary 400 if (mDeferLoadAssociatedPagesUntilScrollCompletes) { 401 loadAssociatedPages(mCurrentPage); 402 mDeferLoadAssociatedPagesUntilScrollCompletes = false; 403 } 404 405 // We don't want to trigger a page end moving unless the page has settled 406 // and the user has stopped scrolling 407 if (mTouchState == TOUCH_STATE_REST) { 408 pageEndMoving(); 409 } 410 411 // Notify the user when the page changes 412 if (AccessibilityManager.getInstance(getContext()).isEnabled()) { 413 AccessibilityEvent ev = 414 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED); 415 ev.getText().add(getCurrentPageDescription()); 416 sendAccessibilityEventUnchecked(ev); 417 } 418 return true; 419 } 420 return false; 421 } 422 423 @Override 424 public void computeScroll() { 425 computeScrollHelper(); 426 } 427 428 @Override 429 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 430 if (!mIsDataReady) { 431 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 432 return; 433 } 434 435 final int widthMode = MeasureSpec.getMode(widthMeasureSpec); 436 final int widthSize = MeasureSpec.getSize(widthMeasureSpec); 437 if (widthMode != MeasureSpec.EXACTLY) { 438 throw new IllegalStateException("Workspace can only be used in EXACTLY mode."); 439 } 440 441 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case 442 * of the All apps view on XLarge displays to not take up more space then it needs. Width 443 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect 444 * each page to have the same width. 445 */ 446 final int heightMode = MeasureSpec.getMode(heightMeasureSpec); 447 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 448 int maxChildHeight = 0; 449 450 final int verticalPadding = mPaddingTop + mPaddingBottom; 451 final int horizontalPadding = mPaddingLeft + mPaddingRight; 452 453 454 // The children are given the same width and height as the workspace 455 // unless they were set to WRAP_CONTENT 456 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize); 457 final int childCount = getChildCount(); 458 for (int i = 0; i < childCount; i++) { 459 // disallowing padding in paged view (just pass 0) 460 final View child = getPageAt(i); 461 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 462 463 int childWidthMode; 464 if (lp.width == LayoutParams.WRAP_CONTENT) { 465 childWidthMode = MeasureSpec.AT_MOST; 466 } else { 467 childWidthMode = MeasureSpec.EXACTLY; 468 } 469 470 int childHeightMode; 471 if (lp.height == LayoutParams.WRAP_CONTENT) { 472 childHeightMode = MeasureSpec.AT_MOST; 473 } else { 474 childHeightMode = MeasureSpec.EXACTLY; 475 } 476 477 final int childWidthMeasureSpec = 478 MeasureSpec.makeMeasureSpec(widthSize - horizontalPadding, childWidthMode); 479 final int childHeightMeasureSpec = 480 MeasureSpec.makeMeasureSpec(heightSize - verticalPadding, childHeightMode); 481 482 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 483 maxChildHeight = Math.max(maxChildHeight, child.getMeasuredHeight()); 484 if (DEBUG) Log.d(TAG, "\tmeasure-child" + i + ": " + child.getMeasuredWidth() + ", " 485 + child.getMeasuredHeight()); 486 } 487 488 if (heightMode == MeasureSpec.AT_MOST) { 489 heightSize = maxChildHeight + verticalPadding; 490 } 491 492 updateScrollingIndicatorPosition(); 493 494 setMeasuredDimension(widthSize, heightSize); 495 496 // We can't call getChildOffset/getRelativeChildOffset until we set the measured dimensions 497 if (childCount > 0) { 498 mMaxScrollX = getChildOffset(childCount - 1) - getRelativeChildOffset(childCount - 1); 499 } else { 500 mMaxScrollX = 0; 501 } 502 } 503 504 protected void scrollToNewPageWithoutMovingPages(int newCurrentPage) { 505 int newX = getChildOffset(newCurrentPage) - getRelativeChildOffset(newCurrentPage); 506 int delta = newX - mScrollX; 507 508 final int pageCount = getChildCount(); 509 for (int i = 0; i < pageCount; i++) { 510 View page = (View) getPageAt(i); 511 page.setX(page.getX() + delta); 512 } 513 setCurrentPage(newCurrentPage); 514 } 515 516 // A layout scale of 1.0f assumes that the pages, in their unshrunken state, have a 517 // scale of 1.0f. A layout scale of 0.8f assumes the pages have a scale of 0.8f, and 518 // tightens the layout accordingly 519 public void setLayoutScale(float childrenScale) { 520 mLayoutScale = childrenScale; 521 522 // Now we need to do a re-layout, but preserving absolute X and Y coordinates 523 int childCount = getChildCount(); 524 float childrenX[] = new float[childCount]; 525 float childrenY[] = new float[childCount]; 526 for (int i = 0; i < childCount; i++) { 527 final View child = getPageAt(i); 528 childrenX[i] = child.getX(); 529 childrenY[i] = child.getY(); 530 } 531 // Trigger a full re-layout (never just call onLayout directly!) 532 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY); 533 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY); 534 requestLayout(); 535 measure(widthSpec, heightSpec); 536 layout(mLeft, mTop, mRight, mBottom); 537 for (int i = 0; i < childCount; i++) { 538 final View child = getPageAt(i); 539 child.setX(childrenX[i]); 540 child.setY(childrenY[i]); 541 } 542 543 // Also, the page offset has changed (since the pages are now smaller); 544 // update the page offset, but again preserving absolute X and Y coordinates 545 scrollToNewPageWithoutMovingPages(mCurrentPage); 546 } 547 548 @Override 549 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 550 if (!mIsDataReady) { 551 return; 552 } 553 554 if (DEBUG) Log.d(TAG, "PagedView.onLayout()"); 555 final int verticalPadding = mPaddingTop + mPaddingBottom; 556 final int childCount = getChildCount(); 557 int childLeft = 0; 558 if (childCount > 0) { 559 if (DEBUG) Log.d(TAG, "getRelativeChildOffset(): " + getMeasuredWidth() + ", " 560 + getChildWidth(0)); 561 childLeft = getRelativeChildOffset(0); 562 563 // Calculate the variable page spacing if necessary 564 if (mPageSpacing < 0) { 565 mPageSpacing = ((right - left) - getChildAt(0).getMeasuredWidth()) / 2; 566 } 567 } 568 569 for (int i = 0; i < childCount; i++) { 570 final View child = getPageAt(i); 571 if (child.getVisibility() != View.GONE) { 572 final int childWidth = getScaledMeasuredWidth(child); 573 final int childHeight = child.getMeasuredHeight(); 574 int childTop = mPaddingTop; 575 if (mCenterPagesVertically) { 576 childTop += ((getMeasuredHeight() - verticalPadding) - childHeight) / 2; 577 } 578 579 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop); 580 child.layout(childLeft, childTop, 581 childLeft + child.getMeasuredWidth(), childTop + childHeight); 582 childLeft += childWidth + mPageSpacing; 583 } 584 } 585 586 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) { 587 setHorizontalScrollBarEnabled(false); 588 int newX = getChildOffset(mCurrentPage) - getRelativeChildOffset(mCurrentPage); 589 scrollTo(newX, 0); 590 mScroller.setFinalX(newX); 591 setHorizontalScrollBarEnabled(true); 592 mFirstLayout = false; 593 } 594 595 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) { 596 mFirstLayout = false; 597 } 598 } 599 600 protected void forceUpdateAdjacentPagesAlpha() { 601 mDirtyPageAlpha = true; 602 updateAdjacentPagesAlpha(); 603 } 604 605 protected void updateAdjacentPagesAlpha() { 606 if (mFadeInAdjacentScreens) { 607 if (mDirtyPageAlpha || (mTouchState == TOUCH_STATE_SCROLLING) || !mScroller.isFinished()) { 608 int screenWidth = getMeasuredWidth() - mPaddingLeft - mPaddingRight; 609 int halfScreenSize = screenWidth / 2; 610 int screenCenter = mScrollX + halfScreenSize + mPaddingLeft; 611 final int childCount = getChildCount(); 612 for (int i = 0; i < childCount; ++i) { 613 View layout = (View) getPageAt(i); 614 int childWidth = getScaledMeasuredWidth(layout); 615 int halfChildWidth = (childWidth / 2); 616 int childCenter = getChildOffset(i) + halfChildWidth; 617 618 // On the first layout, we may not have a width nor a proper offset, so for now 619 // we should just assume full page width (and calculate the offset according to 620 // that). 621 if (childWidth <= 0) { 622 childWidth = screenWidth; 623 childCenter = (i * childWidth) + (childWidth / 2); 624 } 625 626 int d = halfChildWidth; 627 int distanceFromScreenCenter = childCenter - screenCenter; 628 if (distanceFromScreenCenter > 0) { 629 if (i > 0) { 630 d += getScaledMeasuredWidth(getPageAt(i - 1)) / 2; 631 } else { 632 continue; 633 } 634 } else { 635 if (i < childCount - 1) { 636 d += getScaledMeasuredWidth(getPageAt(i + 1)) / 2; 637 } else { 638 continue; 639 } 640 } 641 d += mPageSpacing; 642 643 // Preventing potential divide-by-zero 644 d = Math.max(1, d); 645 646 float dimAlpha = (float) (Math.abs(distanceFromScreenCenter)) / d; 647 dimAlpha = Math.max(0.0f, Math.min(1.0f, (dimAlpha * dimAlpha))); 648 float alpha = 1.0f - dimAlpha; 649 650 if (alpha < ALPHA_QUANTIZE_LEVEL) { 651 alpha = 0.0f; 652 } else if (alpha > 1.0f - ALPHA_QUANTIZE_LEVEL) { 653 alpha = 1.0f; 654 } 655 656 // Due to the way we're setting alpha on our children in PagedViewCellLayout, 657 // this optimization causes alpha to not be properly updated sometimes (repro 658 // case: in xlarge mode, swipe to second page in All Apps, then click on "My 659 // Apps" tab. the page will have alpha 0 until you swipe it). Removing 660 // optimization fixes the issue, but we should fix this in a better manner 661 //if (Float.compare(alpha, layout.getAlpha()) != 0) { 662 layout.setAlpha(alpha); 663 //} 664 } 665 mDirtyPageAlpha = false; 666 } 667 } 668 } 669 670 protected void screenScrolled(int screenCenter) { 671 updateScrollingIndicator(); 672 } 673 674 @Override 675 protected void dispatchDraw(Canvas canvas) { 676 int halfScreenSize = getMeasuredWidth() / 2; 677 int screenCenter = mScrollX + halfScreenSize; 678 679 if (screenCenter != mLastScreenCenter) { 680 screenScrolled(screenCenter); 681 updateAdjacentPagesAlpha(); 682 mLastScreenCenter = screenCenter; 683 } 684 685 // Find out which screens are visible; as an optimization we only call draw on them 686 // As an optimization, this code assumes that all pages have the same width as the 0th 687 // page. 688 final int pageCount = getChildCount(); 689 if (pageCount > 0) { 690 final int pageWidth = getScaledMeasuredWidth(getPageAt(0)); 691 final int screenWidth = getMeasuredWidth(); 692 int x = getScaledRelativeChildOffset(0) + pageWidth; 693 int leftScreen = 0; 694 int rightScreen = 0; 695 while (x <= mScrollX && leftScreen < pageCount - 1) { 696 leftScreen++; 697 x += getScaledMeasuredWidth(getPageAt(leftScreen)) + mPageSpacing; 698 } 699 rightScreen = leftScreen; 700 while (x < mScrollX + screenWidth && rightScreen < pageCount - 1) { 701 rightScreen++; 702 x += getScaledMeasuredWidth(getPageAt(rightScreen)) + mPageSpacing; 703 } 704 rightScreen = Math.min(getChildCount() - 1, rightScreen); 705 706 final long drawingTime = getDrawingTime(); 707 // Clip to the bounds 708 canvas.save(); 709 canvas.clipRect(mScrollX, mScrollY, mScrollX + mRight - mLeft, 710 mScrollY + mBottom - mTop); 711 712 for (int i = rightScreen; i >= leftScreen; i--) { 713 drawChild(canvas, getPageAt(i), drawingTime); 714 } 715 canvas.restore(); 716 } 717 } 718 719 @Override 720 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { 721 int page = indexToPage(indexOfChild(child)); 722 if (page != mCurrentPage || !mScroller.isFinished()) { 723 snapToPage(page); 724 return true; 725 } 726 return false; 727 } 728 729 @Override 730 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { 731 int focusablePage; 732 if (mNextPage != INVALID_PAGE) { 733 focusablePage = mNextPage; 734 } else { 735 focusablePage = mCurrentPage; 736 } 737 View v = getPageAt(focusablePage); 738 if (v != null) { 739 return v.requestFocus(direction, previouslyFocusedRect); 740 } 741 return false; 742 } 743 744 @Override 745 public boolean dispatchUnhandledMove(View focused, int direction) { 746 if (direction == View.FOCUS_LEFT) { 747 if (getCurrentPage() > 0) { 748 snapToPage(getCurrentPage() - 1); 749 return true; 750 } 751 } else if (direction == View.FOCUS_RIGHT) { 752 if (getCurrentPage() < getPageCount() - 1) { 753 snapToPage(getCurrentPage() + 1); 754 return true; 755 } 756 } 757 return super.dispatchUnhandledMove(focused, direction); 758 } 759 760 @Override 761 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 762 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) { 763 getPageAt(mCurrentPage).addFocusables(views, direction); 764 } 765 if (direction == View.FOCUS_LEFT) { 766 if (mCurrentPage > 0) { 767 getPageAt(mCurrentPage - 1).addFocusables(views, direction); 768 } 769 } else if (direction == View.FOCUS_RIGHT){ 770 if (mCurrentPage < getPageCount() - 1) { 771 getPageAt(mCurrentPage + 1).addFocusables(views, direction); 772 } 773 } 774 } 775 776 /** 777 * If one of our descendant views decides that it could be focused now, only 778 * pass that along if it's on the current page. 779 * 780 * This happens when live folders requery, and if they're off page, they 781 * end up calling requestFocus, which pulls it on page. 782 */ 783 @Override 784 public void focusableViewAvailable(View focused) { 785 View current = getPageAt(mCurrentPage); 786 View v = focused; 787 while (true) { 788 if (v == current) { 789 super.focusableViewAvailable(focused); 790 return; 791 } 792 if (v == this) { 793 return; 794 } 795 ViewParent parent = v.getParent(); 796 if (parent instanceof View) { 797 v = (View)v.getParent(); 798 } else { 799 return; 800 } 801 } 802 } 803 804 /** 805 * {@inheritDoc} 806 */ 807 @Override 808 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 809 if (disallowIntercept) { 810 // We need to make sure to cancel our long press if 811 // a scrollable widget takes over touch events 812 final View currentPage = getPageAt(mCurrentPage); 813 currentPage.cancelLongPress(); 814 } 815 super.requestDisallowInterceptTouchEvent(disallowIntercept); 816 } 817 818 /** 819 * Return true if a tap at (x, y) should trigger a flip to the previous page. 820 */ 821 protected boolean hitsPreviousPage(float x, float y) { 822 return (x < getRelativeChildOffset(mCurrentPage) - mPageSpacing); 823 } 824 825 /** 826 * Return true if a tap at (x, y) should trigger a flip to the next page. 827 */ 828 protected boolean hitsNextPage(float x, float y) { 829 return (x > (getMeasuredWidth() - getRelativeChildOffset(mCurrentPage) + mPageSpacing)); 830 } 831 832 @Override 833 public boolean onInterceptTouchEvent(MotionEvent ev) { 834 /* 835 * This method JUST determines whether we want to intercept the motion. 836 * If we return true, onTouchEvent will be called and we do the actual 837 * scrolling there. 838 */ 839 acquireVelocityTrackerAndAddMovement(ev); 840 841 // Skip touch handling if there are no pages to swipe 842 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev); 843 844 /* 845 * Shortcut the most recurring case: the user is in the dragging 846 * state and he is moving his finger. We want to intercept this 847 * motion. 848 */ 849 final int action = ev.getAction(); 850 if ((action == MotionEvent.ACTION_MOVE) && 851 (mTouchState == TOUCH_STATE_SCROLLING)) { 852 return true; 853 } 854 855 switch (action & MotionEvent.ACTION_MASK) { 856 case MotionEvent.ACTION_MOVE: { 857 /* 858 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check 859 * whether the user has moved far enough from his original down touch. 860 */ 861 if (mActivePointerId != INVALID_POINTER) { 862 determineScrollingStart(ev); 863 break; 864 } 865 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN 866 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN 867 // i.e. fall through to the next case (don't break) 868 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events 869 // while it's small- this was causing a crash before we checked for INVALID_POINTER) 870 } 871 872 case MotionEvent.ACTION_DOWN: { 873 final float x = ev.getX(); 874 final float y = ev.getY(); 875 // Remember location of down touch 876 mDownMotionX = x; 877 mLastMotionX = x; 878 mLastMotionY = y; 879 mLastMotionXRemainder = 0; 880 mTotalMotionX = 0; 881 mActivePointerId = ev.getPointerId(0); 882 mAllowLongPress = true; 883 884 /* 885 * If being flinged and user touches the screen, initiate drag; 886 * otherwise don't. mScroller.isFinished should be false when 887 * being flinged. 888 */ 889 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX()); 890 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop); 891 if (finishedScrolling) { 892 mTouchState = TOUCH_STATE_REST; 893 mScroller.abortAnimation(); 894 } else { 895 mTouchState = TOUCH_STATE_SCROLLING; 896 } 897 898 // check if this can be the beginning of a tap on the side of the pages 899 // to scroll the current page 900 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) { 901 if (getChildCount() > 0) { 902 if (hitsPreviousPage(x, y)) { 903 mTouchState = TOUCH_STATE_PREV_PAGE; 904 } else if (hitsNextPage(x, y)) { 905 mTouchState = TOUCH_STATE_NEXT_PAGE; 906 } 907 } 908 } 909 break; 910 } 911 912 case MotionEvent.ACTION_UP: 913 case MotionEvent.ACTION_CANCEL: 914 mTouchState = TOUCH_STATE_REST; 915 mAllowLongPress = false; 916 mActivePointerId = INVALID_POINTER; 917 releaseVelocityTracker(); 918 break; 919 920 case MotionEvent.ACTION_POINTER_UP: 921 onSecondaryPointerUp(ev); 922 releaseVelocityTracker(); 923 break; 924 } 925 926 /* 927 * The only time we want to intercept motion events is if we are in the 928 * drag mode. 929 */ 930 return mTouchState != TOUCH_STATE_REST; 931 } 932 933 protected void animateClickFeedback(View v, final Runnable r) { 934 // animate the view slightly to show click feedback running some logic after it is "pressed" 935 ObjectAnimator anim = (ObjectAnimator) AnimatorInflater. 936 loadAnimator(mContext, R.anim.paged_view_click_feedback); 937 anim.setTarget(v); 938 anim.addListener(new AnimatorListenerAdapter() { 939 public void onAnimationRepeat(Animator animation) { 940 r.run(); 941 } 942 }); 943 anim.start(); 944 } 945 946 protected void determineScrollingStart(MotionEvent ev) { 947 determineScrollingStart(ev, 1.0f); 948 } 949 950 /* 951 * Determines if we should change the touch state to start scrolling after the 952 * user moves their touch point too far. 953 */ 954 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) { 955 /* 956 * Locally do absolute value. mLastMotionX is set to the y value 957 * of the down event. 958 */ 959 final int pointerIndex = ev.findPointerIndex(mActivePointerId); 960 if (pointerIndex == -1) { 961 return; 962 } 963 final float x = ev.getX(pointerIndex); 964 final float y = ev.getY(pointerIndex); 965 final int xDiff = (int) Math.abs(x - mLastMotionX); 966 final int yDiff = (int) Math.abs(y - mLastMotionY); 967 968 final int touchSlop = Math.round(touchSlopScale * mTouchSlop); 969 boolean xPaged = xDiff > mPagingTouchSlop; 970 boolean xMoved = xDiff > touchSlop; 971 boolean yMoved = yDiff > touchSlop; 972 973 if (xMoved || xPaged || yMoved) { 974 if (mUsePagingTouchSlop ? xPaged : xMoved) { 975 // Scroll if the user moved far enough along the X axis 976 mTouchState = TOUCH_STATE_SCROLLING; 977 mTotalMotionX += Math.abs(mLastMotionX - x); 978 mLastMotionX = x; 979 mLastMotionXRemainder = 0; 980 mTouchX = mScrollX; 981 mSmoothingTime = System.nanoTime() / NANOTIME_DIV; 982 pageBeginMoving(); 983 } 984 // Either way, cancel any pending longpress 985 cancelCurrentPageLongPress(); 986 } 987 } 988 989 protected void cancelCurrentPageLongPress() { 990 if (mAllowLongPress) { 991 mAllowLongPress = false; 992 // Try canceling the long press. It could also have been scheduled 993 // by a distant descendant, so use the mAllowLongPress flag to block 994 // everything 995 final View currentPage = getPageAt(mCurrentPage); 996 if (currentPage != null) { 997 currentPage.cancelLongPress(); 998 } 999 } 1000 } 1001 1002 protected float getScrollProgress(int screenCenter, View v, int page) { 1003 final int halfScreenSize = getMeasuredWidth() / 2; 1004 1005 int totalDistance = getScaledMeasuredWidth(v) + mPageSpacing; 1006 int delta = screenCenter - (getChildOffset(page) - 1007 getRelativeChildOffset(page) + halfScreenSize); 1008 1009 float scrollProgress = delta / (totalDistance * 1.0f); 1010 scrollProgress = Math.min(scrollProgress, 1.0f); 1011 scrollProgress = Math.max(scrollProgress, -1.0f); 1012 return scrollProgress; 1013 } 1014 1015 // This curve determines how the effect of scrolling over the limits of the page dimishes 1016 // as the user pulls further and further from the bounds 1017 private float overScrollInfluenceCurve(float f) { 1018 f -= 1.0f; 1019 return f * f * f + 1.0f; 1020 } 1021 1022 protected void acceleratedOverScroll(float amount) { 1023 int screenSize = getMeasuredWidth(); 1024 1025 // We want to reach the max over scroll effect when the user has 1026 // over scrolled half the size of the screen 1027 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize); 1028 1029 if (f == 0) return; 1030 1031 // Clamp this factor, f, to -1 < f < 1 1032 if (Math.abs(f) >= 1) { 1033 f /= Math.abs(f); 1034 } 1035 1036 int overScrollAmount = (int) Math.round(f * screenSize); 1037 if (amount < 0) { 1038 mScrollX = overScrollAmount; 1039 } else { 1040 mScrollX = mMaxScrollX + overScrollAmount; 1041 } 1042 invalidate(); 1043 } 1044 1045 protected void dampedOverScroll(float amount) { 1046 int screenSize = getMeasuredWidth(); 1047 1048 float f = (amount / screenSize); 1049 1050 if (f == 0) return; 1051 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f))); 1052 1053 // Clamp this factor, f, to -1 < f < 1 1054 if (Math.abs(f) >= 1) { 1055 f /= Math.abs(f); 1056 } 1057 1058 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize); 1059 if (amount < 0) { 1060 mScrollX = overScrollAmount; 1061 } else { 1062 mScrollX = mMaxScrollX + overScrollAmount; 1063 } 1064 invalidate(); 1065 } 1066 1067 protected void overScroll(float amount) { 1068 dampedOverScroll(amount); 1069 } 1070 1071 protected float maxOverScroll() { 1072 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not 1073 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect 1074 float f = 1.0f; 1075 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f))); 1076 return OVERSCROLL_DAMP_FACTOR * f; 1077 } 1078 1079 @Override 1080 public boolean onTouchEvent(MotionEvent ev) { 1081 // Skip touch handling if there are no pages to swipe 1082 if (getChildCount() <= 0) return super.onTouchEvent(ev); 1083 1084 acquireVelocityTrackerAndAddMovement(ev); 1085 1086 final int action = ev.getAction(); 1087 1088 switch (action & MotionEvent.ACTION_MASK) { 1089 case MotionEvent.ACTION_DOWN: 1090 /* 1091 * If being flinged and user touches, stop the fling. isFinished 1092 * will be false if being flinged. 1093 */ 1094 if (!mScroller.isFinished()) { 1095 mScroller.abortAnimation(); 1096 } 1097 1098 // Remember where the motion event started 1099 mDownMotionX = mLastMotionX = ev.getX(); 1100 mLastMotionXRemainder = 0; 1101 mTotalMotionX = 0; 1102 mActivePointerId = ev.getPointerId(0); 1103 if (mTouchState == TOUCH_STATE_SCROLLING) { 1104 pageBeginMoving(); 1105 } 1106 break; 1107 1108 case MotionEvent.ACTION_MOVE: 1109 if (mTouchState == TOUCH_STATE_SCROLLING) { 1110 // Scroll to follow the motion event 1111 final int pointerIndex = ev.findPointerIndex(mActivePointerId); 1112 final float x = ev.getX(pointerIndex); 1113 final float deltaX = mLastMotionX + mLastMotionXRemainder - x; 1114 1115 mTotalMotionX += Math.abs(deltaX); 1116 1117 // Only scroll and update mLastMotionX if we have moved some discrete amount. We 1118 // keep the remainder because we are actually testing if we've moved from the last 1119 // scrolled position (which is discrete). 1120 if (Math.abs(deltaX) >= 1.0f) { 1121 mTouchX += deltaX; 1122 mSmoothingTime = System.nanoTime() / NANOTIME_DIV; 1123 if (!mDeferScrollUpdate) { 1124 scrollBy((int) deltaX, 0); 1125 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX); 1126 } else { 1127 invalidate(); 1128 } 1129 mLastMotionX = x; 1130 mLastMotionXRemainder = deltaX - (int) deltaX; 1131 } else { 1132 awakenScrollBars(); 1133 } 1134 } else { 1135 determineScrollingStart(ev); 1136 } 1137 break; 1138 1139 case MotionEvent.ACTION_UP: 1140 if (mTouchState == TOUCH_STATE_SCROLLING) { 1141 final int activePointerId = mActivePointerId; 1142 final int pointerIndex = ev.findPointerIndex(activePointerId); 1143 final float x = ev.getX(pointerIndex); 1144 final VelocityTracker velocityTracker = mVelocityTracker; 1145 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 1146 int velocityX = (int) velocityTracker.getXVelocity(activePointerId); 1147 final int deltaX = (int) (x - mDownMotionX); 1148 boolean isSignificantMove = Math.abs(deltaX) > MIN_LENGTH_FOR_MOVE; 1149 final int snapVelocity = mSnapVelocity; 1150 1151 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x); 1152 1153 // In the case that the page is moved far to one direction and then is flung 1154 // in the opposite direction, we use a threshold to determine whether we should 1155 // just return to the starting page, or if we should skip one further. 1156 boolean returnToOriginalPage = false; 1157 final int pageWidth = getScaledMeasuredWidth(getPageAt(mCurrentPage)); 1158 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD && 1159 Math.signum(velocityX) != Math.signum(deltaX)) { 1160 returnToOriginalPage = true; 1161 } 1162 1163 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING && 1164 Math.abs(velocityX) > snapVelocity; 1165 1166 int finalPage; 1167 // We give flings precedence over large moves, which is why we short-circuit our 1168 // test for a large move if a fling has been registered. That is, a large 1169 // move to the left and fling to the right will register as a fling to the right. 1170 if (((isSignificantMove && deltaX > 0 && !isFling) || 1171 (isFling && velocityX > 0)) && mCurrentPage > 0) { 1172 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1; 1173 snapToPageWithVelocity(finalPage, velocityX); 1174 } else if (((isSignificantMove && deltaX < 0 && !isFling) || 1175 (isFling && velocityX < 0)) && 1176 mCurrentPage < getChildCount() - 1) { 1177 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1; 1178 snapToPageWithVelocity(finalPage, velocityX); 1179 } else { 1180 snapToDestination(); 1181 } 1182 } else if (mTouchState == TOUCH_STATE_PREV_PAGE) { 1183 // at this point we have not moved beyond the touch slop 1184 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so 1185 // we can just page 1186 int nextPage = Math.max(0, mCurrentPage - 1); 1187 if (nextPage != mCurrentPage) { 1188 snapToPage(nextPage); 1189 } else { 1190 snapToDestination(); 1191 } 1192 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) { 1193 // at this point we have not moved beyond the touch slop 1194 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so 1195 // we can just page 1196 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1); 1197 if (nextPage != mCurrentPage) { 1198 snapToPage(nextPage); 1199 } else { 1200 snapToDestination(); 1201 } 1202 } else { 1203 onUnhandledTap(ev); 1204 } 1205 mTouchState = TOUCH_STATE_REST; 1206 mActivePointerId = INVALID_POINTER; 1207 releaseVelocityTracker(); 1208 break; 1209 1210 case MotionEvent.ACTION_CANCEL: 1211 if (mTouchState == TOUCH_STATE_SCROLLING) { 1212 snapToDestination(); 1213 } 1214 mTouchState = TOUCH_STATE_REST; 1215 mActivePointerId = INVALID_POINTER; 1216 releaseVelocityTracker(); 1217 break; 1218 1219 case MotionEvent.ACTION_POINTER_UP: 1220 onSecondaryPointerUp(ev); 1221 break; 1222 } 1223 1224 return true; 1225 } 1226 1227 @Override 1228 public boolean onGenericMotionEvent(MotionEvent event) { 1229 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 1230 switch (event.getAction()) { 1231 case MotionEvent.ACTION_SCROLL: { 1232 // Handle mouse (or ext. device) by shifting the page depending on the scroll 1233 final float vscroll; 1234 final float hscroll; 1235 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) { 1236 vscroll = 0; 1237 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL); 1238 } else { 1239 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL); 1240 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL); 1241 } 1242 if (hscroll != 0 || vscroll != 0) { 1243 if (hscroll > 0 || vscroll > 0) { 1244 scrollRight(); 1245 } else { 1246 scrollLeft(); 1247 } 1248 return true; 1249 } 1250 } 1251 } 1252 } 1253 return super.onGenericMotionEvent(event); 1254 } 1255 1256 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) { 1257 if (mVelocityTracker == null) { 1258 mVelocityTracker = VelocityTracker.obtain(); 1259 } 1260 mVelocityTracker.addMovement(ev); 1261 } 1262 1263 private void releaseVelocityTracker() { 1264 if (mVelocityTracker != null) { 1265 mVelocityTracker.recycle(); 1266 mVelocityTracker = null; 1267 } 1268 } 1269 1270 private void onSecondaryPointerUp(MotionEvent ev) { 1271 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> 1272 MotionEvent.ACTION_POINTER_INDEX_SHIFT; 1273 final int pointerId = ev.getPointerId(pointerIndex); 1274 if (pointerId == mActivePointerId) { 1275 // This was our active pointer going up. Choose a new 1276 // active pointer and adjust accordingly. 1277 // TODO: Make this decision more intelligent. 1278 final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 1279 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex); 1280 mLastMotionY = ev.getY(newPointerIndex); 1281 mLastMotionXRemainder = 0; 1282 mActivePointerId = ev.getPointerId(newPointerIndex); 1283 if (mVelocityTracker != null) { 1284 mVelocityTracker.clear(); 1285 } 1286 } 1287 } 1288 1289 protected void onUnhandledTap(MotionEvent ev) {} 1290 1291 @Override 1292 public void requestChildFocus(View child, View focused) { 1293 super.requestChildFocus(child, focused); 1294 int page = indexToPage(indexOfChild(child)); 1295 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) { 1296 snapToPage(page); 1297 } 1298 } 1299 1300 protected int getChildIndexForRelativeOffset(int relativeOffset) { 1301 final int childCount = getChildCount(); 1302 int left; 1303 int right; 1304 for (int i = 0; i < childCount; ++i) { 1305 left = getRelativeChildOffset(i); 1306 right = (left + getScaledMeasuredWidth(getPageAt(i))); 1307 if (left <= relativeOffset && relativeOffset <= right) { 1308 return i; 1309 } 1310 } 1311 return -1; 1312 } 1313 1314 protected void setMinimumWidthOverride(int minimumWidth) { 1315 mMinimumWidth = minimumWidth; 1316 } 1317 protected void resetMinimumWidthOverride() { 1318 mMinimumWidth = 0; 1319 } 1320 1321 protected int getChildWidth(int index) { 1322 // This functions are called enough times that it actually makes a difference in the 1323 // profiler -- so just inline the max() here 1324 final int measuredWidth = getPageAt(index).getMeasuredWidth(); 1325 final int minWidth = mMinimumWidth; 1326 return (minWidth > measuredWidth) ? minWidth : measuredWidth; 1327 } 1328 1329 protected int getRelativeChildOffset(int index) { 1330 int padding = mPaddingLeft + mPaddingRight; 1331 return mPaddingLeft + (getMeasuredWidth() - padding - getChildWidth(index)) / 2; 1332 } 1333 protected int getScaledRelativeChildOffset(int index) { 1334 int padding = mPaddingLeft + mPaddingRight; 1335 return mPaddingLeft + (getMeasuredWidth() - padding - 1336 getScaledMeasuredWidth(getPageAt(index))) / 2; 1337 } 1338 1339 protected int getChildOffset(int index) { 1340 if (getChildCount() == 0) 1341 return 0; 1342 1343 int offset = getRelativeChildOffset(0); 1344 for (int i = 0; i < index; ++i) { 1345 offset += getScaledMeasuredWidth(getPageAt(i)) + mPageSpacing; 1346 } 1347 return offset; 1348 } 1349 1350 protected int getScaledMeasuredWidth(View child) { 1351 // This functions are called enough times that it actually makes a difference in the 1352 // profiler -- so just inline the max() here 1353 final int measuredWidth = child.getMeasuredWidth(); 1354 final int minWidth = mMinimumWidth; 1355 final int maxWidth = (minWidth > measuredWidth) ? minWidth : measuredWidth; 1356 return (int) (maxWidth * mLayoutScale + 0.5f); 1357 } 1358 1359 int getPageNearestToCenterOfScreen() { 1360 int minDistanceFromScreenCenter = Integer.MAX_VALUE; 1361 int minDistanceFromScreenCenterIndex = -1; 1362 int screenCenter = mScrollX + (getMeasuredWidth() / 2); 1363 final int childCount = getChildCount(); 1364 for (int i = 0; i < childCount; ++i) { 1365 View layout = (View) getPageAt(i); 1366 int childWidth = getScaledMeasuredWidth(layout); 1367 int halfChildWidth = (childWidth / 2); 1368 int childCenter = getChildOffset(i) + halfChildWidth; 1369 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter); 1370 if (distanceFromScreenCenter < minDistanceFromScreenCenter) { 1371 minDistanceFromScreenCenter = distanceFromScreenCenter; 1372 minDistanceFromScreenCenterIndex = i; 1373 } 1374 } 1375 return minDistanceFromScreenCenterIndex; 1376 } 1377 1378 protected void snapToDestination() { 1379 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION); 1380 } 1381 1382 private static class ScrollInterpolator implements Interpolator { 1383 public ScrollInterpolator() { 1384 } 1385 1386 public float getInterpolation(float t) { 1387 t -= 1.0f; 1388 return t*t*t*t*t + 1; 1389 } 1390 } 1391 1392 // We want the duration of the page snap animation to be influenced by the distance that 1393 // the screen has to travel, however, we don't want this duration to be effected in a 1394 // purely linear fashion. Instead, we use this method to moderate the effect that the distance 1395 // of travel has on the overall snap duration. 1396 float distanceInfluenceForSnapDuration(float f) { 1397 f -= 0.5f; // center the values about 0. 1398 f *= 0.3f * Math.PI / 2.0f; 1399 return (float) Math.sin(f); 1400 } 1401 1402 protected void snapToPageWithVelocity(int whichPage, int velocity) { 1403 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1)); 1404 int halfScreenSize = getMeasuredWidth() / 2; 1405 1406 if (DEBUG) Log.d(TAG, "snapToPage.getChildOffset(): " + getChildOffset(whichPage)); 1407 if (DEBUG) Log.d(TAG, "snapToPageWithVelocity.getRelativeChildOffset(): " 1408 + getMeasuredWidth() + ", " + getChildWidth(whichPage)); 1409 final int newX = getChildOffset(whichPage) - getRelativeChildOffset(whichPage); 1410 int delta = newX - mUnboundedScrollX; 1411 int duration = 0; 1412 1413 if (Math.abs(velocity) < MIN_FLING_VELOCITY) { 1414 // If the velocity is low enough, then treat this more as an automatic page advance 1415 // as opposed to an apparent physical response to flinging 1416 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION); 1417 return; 1418 } 1419 1420 // Here we compute a "distance" that will be used in the computation of the overall 1421 // snap duration. This is a function of the actual distance that needs to be traveled; 1422 // we keep this value close to half screen size in order to reduce the variance in snap 1423 // duration as a function of the distance the page needs to travel. 1424 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize)); 1425 float distance = halfScreenSize + halfScreenSize * 1426 distanceInfluenceForSnapDuration(distanceRatio); 1427 1428 velocity = Math.abs(velocity); 1429 velocity = Math.max(MINIMUM_SNAP_VELOCITY, velocity); 1430 1431 // we want the page's snap velocity to approximately match the velocity at which the 1432 // user flings, so we scale the duration by a value near to the derivative of the scroll 1433 // interpolator at zero, ie. 5. We use 4 to make it a little slower. 1434 duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); 1435 1436 snapToPage(whichPage, delta, duration); 1437 } 1438 1439 protected void snapToPage(int whichPage) { 1440 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION); 1441 } 1442 1443 protected void snapToPage(int whichPage, int duration) { 1444 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1)); 1445 1446 if (DEBUG) Log.d(TAG, "snapToPage.getChildOffset(): " + getChildOffset(whichPage)); 1447 if (DEBUG) Log.d(TAG, "snapToPage.getRelativeChildOffset(): " + getMeasuredWidth() + ", " 1448 + getChildWidth(whichPage)); 1449 int newX = getChildOffset(whichPage) - getRelativeChildOffset(whichPage); 1450 final int sX = mUnboundedScrollX; 1451 final int delta = newX - sX; 1452 snapToPage(whichPage, delta, duration); 1453 } 1454 1455 protected void snapToPage(int whichPage, int delta, int duration) { 1456 mNextPage = whichPage; 1457 1458 View focusedChild = getFocusedChild(); 1459 if (focusedChild != null && whichPage != mCurrentPage && 1460 focusedChild == getPageAt(mCurrentPage)) { 1461 focusedChild.clearFocus(); 1462 } 1463 1464 pageBeginMoving(); 1465 awakenScrollBars(duration); 1466 if (duration == 0) { 1467 duration = Math.abs(delta); 1468 } 1469 1470 if (!mScroller.isFinished()) mScroller.abortAnimation(); 1471 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration); 1472 1473 // Load associated pages immediately if someone else is handling the scroll, otherwise defer 1474 // loading associated pages until the scroll settles 1475 if (mDeferScrollUpdate) { 1476 loadAssociatedPages(mNextPage); 1477 } else { 1478 mDeferLoadAssociatedPagesUntilScrollCompletes = true; 1479 } 1480 notifyPageSwitchListener(); 1481 invalidate(); 1482 } 1483 1484 public void scrollLeft() { 1485 if (mScroller.isFinished()) { 1486 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1); 1487 } else { 1488 if (mNextPage > 0) snapToPage(mNextPage - 1); 1489 } 1490 } 1491 1492 public void scrollRight() { 1493 if (mScroller.isFinished()) { 1494 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1); 1495 } else { 1496 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1); 1497 } 1498 } 1499 1500 public int getPageForView(View v) { 1501 int result = -1; 1502 if (v != null) { 1503 ViewParent vp = v.getParent(); 1504 int count = getChildCount(); 1505 for (int i = 0; i < count; i++) { 1506 if (vp == getPageAt(i)) { 1507 return i; 1508 } 1509 } 1510 } 1511 return result; 1512 } 1513 1514 /** 1515 * @return True is long presses are still allowed for the current touch 1516 */ 1517 public boolean allowLongPress() { 1518 return mAllowLongPress; 1519 } 1520 1521 /** 1522 * Set true to allow long-press events to be triggered, usually checked by 1523 * {@link Launcher} to accept or block dpad-initiated long-presses. 1524 */ 1525 public void setAllowLongPress(boolean allowLongPress) { 1526 mAllowLongPress = allowLongPress; 1527 } 1528 1529 public static class SavedState extends BaseSavedState { 1530 int currentPage = -1; 1531 1532 SavedState(Parcelable superState) { 1533 super(superState); 1534 } 1535 1536 private SavedState(Parcel in) { 1537 super(in); 1538 currentPage = in.readInt(); 1539 } 1540 1541 @Override 1542 public void writeToParcel(Parcel out, int flags) { 1543 super.writeToParcel(out, flags); 1544 out.writeInt(currentPage); 1545 } 1546 1547 public static final Parcelable.Creator<SavedState> CREATOR = 1548 new Parcelable.Creator<SavedState>() { 1549 public SavedState createFromParcel(Parcel in) { 1550 return new SavedState(in); 1551 } 1552 1553 public SavedState[] newArray(int size) { 1554 return new SavedState[size]; 1555 } 1556 }; 1557 } 1558 1559 protected void loadAssociatedPages(int page) { 1560 loadAssociatedPages(page, false); 1561 } 1562 protected void loadAssociatedPages(int page, boolean immediateAndOnly) { 1563 if (mContentIsRefreshable) { 1564 final int count = getChildCount(); 1565 if (page < count) { 1566 int lowerPageBound = getAssociatedLowerPageBound(page); 1567 int upperPageBound = getAssociatedUpperPageBound(page); 1568 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/" 1569 + upperPageBound); 1570 for (int i = 0; i < count; ++i) { 1571 if ((i != page) && immediateAndOnly) { 1572 continue; 1573 } 1574 Page layout = (Page) getPageAt(i); 1575 final int childCount = layout.getPageChildCount(); 1576 if (lowerPageBound <= i && i <= upperPageBound) { 1577 if (mDirtyPageContent.get(i)) { 1578 syncPageItems(i, (i == page) && immediateAndOnly); 1579 mDirtyPageContent.set(i, false); 1580 } 1581 } else { 1582 if (childCount > 0) { 1583 layout.removeAllViewsOnPage(); 1584 } 1585 mDirtyPageContent.set(i, true); 1586 } 1587 } 1588 } 1589 } 1590 } 1591 1592 protected int getAssociatedLowerPageBound(int page) { 1593 return Math.max(0, page - 1); 1594 } 1595 protected int getAssociatedUpperPageBound(int page) { 1596 final int count = getChildCount(); 1597 return Math.min(page + 1, count - 1); 1598 } 1599 1600 protected void startChoiceMode(int mode, ActionMode.Callback callback) { 1601 if (isChoiceMode(CHOICE_MODE_NONE)) { 1602 mChoiceMode = mode; 1603 mActionMode = startActionMode(callback); 1604 } 1605 } 1606 1607 public void endChoiceMode() { 1608 if (!isChoiceMode(CHOICE_MODE_NONE)) { 1609 mChoiceMode = CHOICE_MODE_NONE; 1610 resetCheckedGrandchildren(); 1611 if (mActionMode != null) mActionMode.finish(); 1612 mActionMode = null; 1613 } 1614 } 1615 1616 protected boolean isChoiceMode(int mode) { 1617 return mChoiceMode == mode; 1618 } 1619 1620 protected ArrayList<Checkable> getCheckedGrandchildren() { 1621 ArrayList<Checkable> checked = new ArrayList<Checkable>(); 1622 final int childCount = getChildCount(); 1623 for (int i = 0; i < childCount; ++i) { 1624 Page layout = (Page) getPageAt(i); 1625 final int grandChildCount = layout.getPageChildCount(); 1626 for (int j = 0; j < grandChildCount; ++j) { 1627 final View v = layout.getChildOnPageAt(j); 1628 if (v instanceof Checkable && ((Checkable) v).isChecked()) { 1629 checked.add((Checkable) v); 1630 } 1631 } 1632 } 1633 return checked; 1634 } 1635 1636 /** 1637 * If in CHOICE_MODE_SINGLE and an item is checked, returns that item. 1638 * Otherwise, returns null. 1639 */ 1640 protected Checkable getSingleCheckedGrandchild() { 1641 if (mChoiceMode != CHOICE_MODE_MULTIPLE) { 1642 final int childCount = getChildCount(); 1643 for (int i = 0; i < childCount; ++i) { 1644 Page layout = (Page) getPageAt(i); 1645 final int grandChildCount = layout.getPageChildCount(); 1646 for (int j = 0; j < grandChildCount; ++j) { 1647 final View v = layout.getChildOnPageAt(j); 1648 if (v instanceof Checkable && ((Checkable) v).isChecked()) { 1649 return (Checkable) v; 1650 } 1651 } 1652 } 1653 } 1654 return null; 1655 } 1656 1657 protected void resetCheckedGrandchildren() { 1658 // loop through children, and set all of their children to _not_ be checked 1659 final ArrayList<Checkable> checked = getCheckedGrandchildren(); 1660 for (int i = 0; i < checked.size(); ++i) { 1661 final Checkable c = checked.get(i); 1662 c.setChecked(false); 1663 } 1664 } 1665 1666 /** 1667 * This method is called ONLY to synchronize the number of pages that the paged view has. 1668 * To actually fill the pages with information, implement syncPageItems() below. It is 1669 * guaranteed that syncPageItems() will be called for a particular page before it is shown, 1670 * and therefore, individual page items do not need to be updated in this method. 1671 */ 1672 public abstract void syncPages(); 1673 1674 /** 1675 * This method is called to synchronize the items that are on a particular page. If views on 1676 * the page can be reused, then they should be updated within this method. 1677 */ 1678 public abstract void syncPageItems(int page, boolean immediate); 1679 1680 protected void invalidatePageData() { 1681 invalidatePageData(-1, false); 1682 } 1683 protected void invalidatePageData(int currentPage) { 1684 invalidatePageData(currentPage, false); 1685 } 1686 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) { 1687 if (!mIsDataReady) { 1688 return; 1689 } 1690 1691 if (mContentIsRefreshable) { 1692 // Force all scrolling-related behavior to end 1693 mScroller.forceFinished(true); 1694 mNextPage = INVALID_PAGE; 1695 1696 // Update all the pages 1697 syncPages(); 1698 1699 // We must force a measure after we've loaded the pages to update the content width and 1700 // to determine the full scroll width 1701 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY), 1702 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY)); 1703 1704 // Set a new page as the current page if necessary 1705 if (currentPage > -1) { 1706 setCurrentPage(Math.min(getPageCount() - 1, currentPage)); 1707 } 1708 1709 // Mark each of the pages as dirty 1710 final int count = getChildCount(); 1711 mDirtyPageContent.clear(); 1712 for (int i = 0; i < count; ++i) { 1713 mDirtyPageContent.add(true); 1714 } 1715 1716 // Load any pages that are necessary for the current window of views 1717 loadAssociatedPages(mCurrentPage, immediateAndOnly); 1718 mDirtyPageAlpha = true; 1719 updateAdjacentPagesAlpha(); 1720 requestLayout(); 1721 } 1722 } 1723 1724 private ImageView getScrollingIndicator() { 1725 // We use mHasScrollIndicator to prevent future lookups if there is no sibling indicator 1726 // found 1727 if (mHasScrollIndicator && mScrollIndicator == null) { 1728 ViewGroup parent = (ViewGroup) getParent(); 1729 mScrollIndicator = (ImageView) (parent.findViewById(R.id.paged_view_indicator)); 1730 mHasScrollIndicator = mScrollIndicator != null; 1731 if (mHasScrollIndicator) { 1732 mScrollIndicator.setVisibility(View.VISIBLE); 1733 } 1734 } 1735 return mScrollIndicator; 1736 } 1737 1738 protected boolean isScrollingIndicatorEnabled() { 1739 return !LauncherApplication.isScreenLarge(); 1740 } 1741 1742 Runnable hideScrollingIndicatorRunnable = new Runnable() { 1743 @Override 1744 public void run() { 1745 hideScrollingIndicator(false); 1746 } 1747 }; 1748 protected void flashScrollingIndicator() { 1749 removeCallbacks(hideScrollingIndicatorRunnable); 1750 showScrollingIndicator(false); 1751 postDelayed(hideScrollingIndicatorRunnable, sScrollIndicatorFlashDuration); 1752 } 1753 1754 protected void showScrollingIndicator(boolean immediately) { 1755 if (getChildCount() <= 1) return; 1756 if (!isScrollingIndicatorEnabled()) return; 1757 1758 getScrollingIndicator(); 1759 if (mScrollIndicator != null) { 1760 // Fade the indicator in 1761 updateScrollingIndicatorPosition(); 1762 mScrollIndicator.setVisibility(View.VISIBLE); 1763 if (mScrollIndicatorAnimator != null) { 1764 mScrollIndicatorAnimator.cancel(); 1765 } 1766 if (immediately) { 1767 mScrollIndicator.setAlpha(1f); 1768 } else { 1769 mScrollIndicatorAnimator = ObjectAnimator.ofFloat(mScrollIndicator, "alpha", 1f); 1770 mScrollIndicatorAnimator.setDuration(sScrollIndicatorFadeInDuration); 1771 mScrollIndicatorAnimator.start(); 1772 } 1773 } 1774 } 1775 1776 protected void hideScrollingIndicator(boolean immediately) { 1777 if (getChildCount() <= 1) return; 1778 if (!isScrollingIndicatorEnabled()) return; 1779 1780 getScrollingIndicator(); 1781 if (mScrollIndicator != null) { 1782 // Fade the indicator out 1783 updateScrollingIndicatorPosition(); 1784 if (mScrollIndicatorAnimator != null) { 1785 mScrollIndicatorAnimator.cancel(); 1786 } 1787 if (immediately) { 1788 mScrollIndicator.setVisibility(View.GONE); 1789 mScrollIndicator.setAlpha(0f); 1790 } else { 1791 mScrollIndicatorAnimator = ObjectAnimator.ofFloat(mScrollIndicator, "alpha", 0f); 1792 mScrollIndicatorAnimator.setDuration(sScrollIndicatorFadeOutDuration); 1793 mScrollIndicatorAnimator.addListener(new AnimatorListenerAdapter() { 1794 private boolean cancelled = false; 1795 @Override 1796 public void onAnimationCancel(android.animation.Animator animation) { 1797 cancelled = true; 1798 } 1799 @Override 1800 public void onAnimationEnd(Animator animation) { 1801 if (!cancelled) { 1802 mScrollIndicator.setVisibility(View.GONE); 1803 } 1804 } 1805 }); 1806 mScrollIndicatorAnimator.start(); 1807 } 1808 } 1809 } 1810 1811 /** 1812 * To be overridden by subclasses to determine whether the scroll indicator should stretch to 1813 * fill its space on the track or not. 1814 */ 1815 protected boolean hasElasticScrollIndicator() { 1816 return true; 1817 } 1818 1819 private void updateScrollingIndicator() { 1820 if (getChildCount() <= 1) return; 1821 if (!isScrollingIndicatorEnabled()) return; 1822 1823 getScrollingIndicator(); 1824 if (mScrollIndicator != null) { 1825 updateScrollingIndicatorPosition(); 1826 } 1827 } 1828 1829 private void updateScrollingIndicatorPosition() { 1830 if (!isScrollingIndicatorEnabled()) return; 1831 if (mScrollIndicator == null) return; 1832 int numPages = getChildCount(); 1833 int pageWidth = getMeasuredWidth(); 1834 int lastChildIndex = Math.max(0, getChildCount() - 1); 1835 int maxScrollX = getChildOffset(lastChildIndex) - getRelativeChildOffset(lastChildIndex); 1836 int trackWidth = pageWidth - mScrollIndicatorPaddingLeft - mScrollIndicatorPaddingRight; 1837 int indicatorWidth = mScrollIndicator.getMeasuredWidth() - 1838 mScrollIndicator.getPaddingLeft() - mScrollIndicator.getPaddingRight(); 1839 1840 float offset = Math.max(0f, Math.min(1f, (float) getScrollX() / maxScrollX)); 1841 int indicatorSpace = trackWidth / numPages; 1842 int indicatorPos = (int) (offset * (trackWidth - indicatorSpace)) + mScrollIndicatorPaddingLeft; 1843 if (hasElasticScrollIndicator()) { 1844 if (mScrollIndicator.getMeasuredWidth() != indicatorSpace) { 1845 mScrollIndicator.getLayoutParams().width = indicatorSpace; 1846 mScrollIndicator.requestLayout(); 1847 } 1848 } else { 1849 int indicatorCenterOffset = indicatorSpace / 2 - indicatorWidth / 2; 1850 indicatorPos += indicatorCenterOffset; 1851 } 1852 mScrollIndicator.setTranslationX(indicatorPos); 1853 mScrollIndicator.invalidate(); 1854 } 1855 1856 public void showScrollIndicatorTrack() { 1857 } 1858 1859 public void hideScrollIndicatorTrack() { 1860 } 1861 1862 /* Accessibility */ 1863 @Override 1864 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 1865 super.onInitializeAccessibilityNodeInfo(info); 1866 info.setScrollable(true); 1867 } 1868 1869 @Override 1870 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 1871 super.onInitializeAccessibilityEvent(event); 1872 event.setScrollable(true); 1873 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) { 1874 event.setFromIndex(mCurrentPage); 1875 event.setToIndex(mCurrentPage); 1876 event.setItemCount(getChildCount()); 1877 } 1878 } 1879 1880 protected String getCurrentPageDescription() { 1881 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 1882 return String.format(mContext.getString(R.string.default_scroll_format), 1883 page + 1, getChildCount()); 1884 } 1885 1886 @Override 1887 public boolean onHoverEvent(android.view.MotionEvent event) { 1888 return true; 1889 } 1890 } 1891