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