ViewPager.java revision f1452d17be15651c6047ec4eb7ff5892538e8265
1/* 2 * Copyright (C) 2011 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 17package android.support.v4.view; 18 19import android.content.Context; 20import android.content.res.Resources; 21import android.content.res.TypedArray; 22import android.database.DataSetObserver; 23import android.graphics.Canvas; 24import android.graphics.Rect; 25import android.graphics.drawable.Drawable; 26import android.os.Build; 27import android.os.Bundle; 28import android.os.Parcel; 29import android.os.Parcelable; 30import android.os.SystemClock; 31import android.support.v4.os.ParcelableCompat; 32import android.support.v4.os.ParcelableCompatCreatorCallbacks; 33import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; 34import android.support.v4.widget.EdgeEffectCompat; 35import android.util.AttributeSet; 36import android.util.Log; 37import android.view.FocusFinder; 38import android.view.Gravity; 39import android.view.KeyEvent; 40import android.view.MotionEvent; 41import android.view.SoundEffectConstants; 42import android.view.VelocityTracker; 43import android.view.View; 44import android.view.ViewConfiguration; 45import android.view.ViewGroup; 46import android.view.ViewParent; 47import android.view.accessibility.AccessibilityEvent; 48import android.view.animation.Interpolator; 49import android.widget.Scroller; 50 51import java.lang.reflect.Method; 52import java.util.ArrayList; 53import java.util.Collections; 54import java.util.Comparator; 55 56/** 57 * Layout manager that allows the user to flip left and right 58 * through pages of data. You supply an implementation of a 59 * {@link PagerAdapter} to generate the pages that the view shows. 60 * 61 * <p>Note this class is currently under early design and 62 * development. The API will likely change in later updates of 63 * the compatibility library, requiring changes to the source code 64 * of apps when they are compiled against the newer version.</p> 65 * 66 * <p>ViewPager is most often used in conjunction with {@link android.app.Fragment}, 67 * which is a convenient way to supply and manage the lifecycle of each page. 68 * There are standard adapters implemented for using fragments with the ViewPager, 69 * which cover the most common use cases. These are 70 * {@link android.support.v4.app.FragmentPagerAdapter}, 71 * {@link android.support.v4.app.FragmentStatePagerAdapter}, 72 * {@link android.support.v13.app.FragmentPagerAdapter}, and 73 * {@link android.support.v13.app.FragmentStatePagerAdapter}; each of these 74 * classes have simple code showing how to build a full user interface 75 * with them. 76 * 77 * <p>Here is a more complicated example of ViewPager, using it in conjuction 78 * with {@link android.app.ActionBar} tabs. You can find other examples of using 79 * ViewPager in the API 4+ Support Demos and API 13+ Support Demos sample code. 80 * 81 * {@sample development/samples/Support13Demos/src/com/example/android/supportv13/app/ActionBarTabsPager.java 82 * complete} 83 */ 84public class ViewPager extends ViewGroup { 85 private static final String TAG = "ViewPager"; 86 private static final boolean DEBUG = false; 87 88 private static final boolean USE_CACHE = false; 89 90 private static final int DEFAULT_OFFSCREEN_PAGES = 1; 91 private static final int MAX_SETTLE_DURATION = 600; // ms 92 private static final int MIN_DISTANCE_FOR_FLING = 25; // dips 93 94 private static final int DEFAULT_GUTTER_SIZE = 16; // dips 95 96 private static final int MIN_FLING_VELOCITY = 400; // dips 97 98 private static final int[] LAYOUT_ATTRS = new int[] { 99 android.R.attr.layout_gravity 100 }; 101 102 /** 103 * Used to track what the expected number of items in the adapter should be. 104 * If the app changes this when we don't expect it, we'll throw a big obnoxious exception. 105 */ 106 private int mExpectedAdapterCount; 107 108 static class ItemInfo { 109 Object object; 110 int position; 111 boolean scrolling; 112 float widthFactor; 113 float offset; 114 } 115 116 private static final Comparator<ItemInfo> COMPARATOR = new Comparator<ItemInfo>(){ 117 @Override 118 public int compare(ItemInfo lhs, ItemInfo rhs) { 119 return lhs.position - rhs.position; 120 } 121 }; 122 123 private static final Interpolator sInterpolator = new Interpolator() { 124 public float getInterpolation(float t) { 125 t -= 1.0f; 126 return t * t * t * t * t + 1.0f; 127 } 128 }; 129 130 private final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>(); 131 private final ItemInfo mTempItem = new ItemInfo(); 132 133 private final Rect mTempRect = new Rect(); 134 135 private PagerAdapter mAdapter; 136 private int mCurItem; // Index of currently displayed page. 137 private int mRestoredCurItem = -1; 138 private Parcelable mRestoredAdapterState = null; 139 private ClassLoader mRestoredClassLoader = null; 140 private Scroller mScroller; 141 private PagerObserver mObserver; 142 143 private int mPageMargin; 144 private Drawable mMarginDrawable; 145 private int mTopPageBounds; 146 private int mBottomPageBounds; 147 148 // Offsets of the first and last items, if known. 149 // Set during population, used to determine if we are at the beginning 150 // or end of the pager data set during touch scrolling. 151 private float mFirstOffset = -Float.MAX_VALUE; 152 private float mLastOffset = Float.MAX_VALUE; 153 154 private int mChildWidthMeasureSpec; 155 private int mChildHeightMeasureSpec; 156 private boolean mInLayout; 157 158 private boolean mScrollingCacheEnabled; 159 160 private boolean mPopulatePending; 161 private int mOffscreenPageLimit = DEFAULT_OFFSCREEN_PAGES; 162 163 private boolean mIsBeingDragged; 164 private boolean mIsUnableToDrag; 165 private boolean mIgnoreGutter; 166 private int mDefaultGutterSize; 167 private int mGutterSize; 168 private int mTouchSlop; 169 /** 170 * Position of the last motion event. 171 */ 172 private float mLastMotionX; 173 private float mLastMotionY; 174 private float mInitialMotionX; 175 private float mInitialMotionY; 176 /** 177 * ID of the active pointer. This is used to retain consistency during 178 * drags/flings if multiple pointers are used. 179 */ 180 private int mActivePointerId = INVALID_POINTER; 181 /** 182 * Sentinel value for no current active pointer. 183 * Used by {@link #mActivePointerId}. 184 */ 185 private static final int INVALID_POINTER = -1; 186 187 /** 188 * Determines speed during touch scrolling 189 */ 190 private VelocityTracker mVelocityTracker; 191 private int mMinimumVelocity; 192 private int mMaximumVelocity; 193 private int mFlingDistance; 194 private int mCloseEnough; 195 196 // If the pager is at least this close to its final position, complete the scroll 197 // on touch down and let the user interact with the content inside instead of 198 // "catching" the flinging pager. 199 private static final int CLOSE_ENOUGH = 2; // dp 200 201 private boolean mFakeDragging; 202 private long mFakeDragBeginTime; 203 204 private EdgeEffectCompat mLeftEdge; 205 private EdgeEffectCompat mRightEdge; 206 207 private boolean mFirstLayout = true; 208 private boolean mNeedCalculatePageOffsets = false; 209 private boolean mCalledSuper; 210 private int mDecorChildCount; 211 212 private OnPageChangeListener mOnPageChangeListener; 213 private OnPageChangeListener mInternalPageChangeListener; 214 private OnAdapterChangeListener mAdapterChangeListener; 215 private PageTransformer mPageTransformer; 216 private Method mSetChildrenDrawingOrderEnabled; 217 218 private static final int DRAW_ORDER_DEFAULT = 0; 219 private static final int DRAW_ORDER_FORWARD = 1; 220 private static final int DRAW_ORDER_REVERSE = 2; 221 private int mDrawingOrder; 222 private ArrayList<View> mDrawingOrderedChildren; 223 private static final ViewPositionComparator sPositionComparator = new ViewPositionComparator(); 224 225 /** 226 * Indicates that the pager is in an idle, settled state. The current page 227 * is fully in view and no animation is in progress. 228 */ 229 public static final int SCROLL_STATE_IDLE = 0; 230 231 /** 232 * Indicates that the pager is currently being dragged by the user. 233 */ 234 public static final int SCROLL_STATE_DRAGGING = 1; 235 236 /** 237 * Indicates that the pager is in the process of settling to a final position. 238 */ 239 public static final int SCROLL_STATE_SETTLING = 2; 240 241 private final Runnable mEndScrollRunnable = new Runnable() { 242 public void run() { 243 setScrollState(SCROLL_STATE_IDLE); 244 populate(); 245 } 246 }; 247 248 private int mScrollState = SCROLL_STATE_IDLE; 249 250 /** 251 * Callback interface for responding to changing state of the selected page. 252 */ 253 public interface OnPageChangeListener { 254 255 /** 256 * This method will be invoked when the current page is scrolled, either as part 257 * of a programmatically initiated smooth scroll or a user initiated touch scroll. 258 * 259 * @param position Position index of the first page currently being displayed. 260 * Page position+1 will be visible if positionOffset is nonzero. 261 * @param positionOffset Value from [0, 1) indicating the offset from the page at position. 262 * @param positionOffsetPixels Value in pixels indicating the offset from position. 263 */ 264 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels); 265 266 /** 267 * This method will be invoked when a new page becomes selected. Animation is not 268 * necessarily complete. 269 * 270 * @param position Position index of the new selected page. 271 */ 272 public void onPageSelected(int position); 273 274 /** 275 * Called when the scroll state changes. Useful for discovering when the user 276 * begins dragging, when the pager is automatically settling to the current page, 277 * or when it is fully stopped/idle. 278 * 279 * @param state The new scroll state. 280 * @see ViewPager#SCROLL_STATE_IDLE 281 * @see ViewPager#SCROLL_STATE_DRAGGING 282 * @see ViewPager#SCROLL_STATE_SETTLING 283 */ 284 public void onPageScrollStateChanged(int state); 285 } 286 287 /** 288 * Simple implementation of the {@link OnPageChangeListener} interface with stub 289 * implementations of each method. Extend this if you do not intend to override 290 * every method of {@link OnPageChangeListener}. 291 */ 292 public static class SimpleOnPageChangeListener implements OnPageChangeListener { 293 @Override 294 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 295 // This space for rent 296 } 297 298 @Override 299 public void onPageSelected(int position) { 300 // This space for rent 301 } 302 303 @Override 304 public void onPageScrollStateChanged(int state) { 305 // This space for rent 306 } 307 } 308 309 /** 310 * A PageTransformer is invoked whenever a visible/attached page is scrolled. 311 * This offers an opportunity for the application to apply a custom transformation 312 * to the page views using animation properties. 313 * 314 * <p>As property animation is only supported as of Android 3.0 and forward, 315 * setting a PageTransformer on a ViewPager on earlier platform versions will 316 * be ignored.</p> 317 */ 318 public interface PageTransformer { 319 /** 320 * Apply a property transformation to the given page. 321 * 322 * @param page Apply the transformation to this page 323 * @param position Position of page relative to the current front-and-center 324 * position of the pager. 0 is front and center. 1 is one full 325 * page position to the right, and -1 is one page position to the left. 326 */ 327 public void transformPage(View page, float position); 328 } 329 330 /** 331 * Used internally to monitor when adapters are switched. 332 */ 333 interface OnAdapterChangeListener { 334 public void onAdapterChanged(PagerAdapter oldAdapter, PagerAdapter newAdapter); 335 } 336 337 /** 338 * Used internally to tag special types of child views that should be added as 339 * pager decorations by default. 340 */ 341 interface Decor {} 342 343 public ViewPager(Context context) { 344 super(context); 345 initViewPager(); 346 } 347 348 public ViewPager(Context context, AttributeSet attrs) { 349 super(context, attrs); 350 initViewPager(); 351 } 352 353 void initViewPager() { 354 setWillNotDraw(false); 355 setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); 356 setFocusable(true); 357 final Context context = getContext(); 358 mScroller = new Scroller(context, sInterpolator); 359 final ViewConfiguration configuration = ViewConfiguration.get(context); 360 final float density = context.getResources().getDisplayMetrics().density; 361 362 mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); 363 mMinimumVelocity = (int) (MIN_FLING_VELOCITY * density); 364 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); 365 mLeftEdge = new EdgeEffectCompat(context); 366 mRightEdge = new EdgeEffectCompat(context); 367 368 mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density); 369 mCloseEnough = (int) (CLOSE_ENOUGH * density); 370 mDefaultGutterSize = (int) (DEFAULT_GUTTER_SIZE * density); 371 372 ViewCompat.setAccessibilityDelegate(this, new MyAccessibilityDelegate()); 373 374 if (ViewCompat.getImportantForAccessibility(this) 375 == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 376 ViewCompat.setImportantForAccessibility(this, 377 ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); 378 } 379 } 380 381 @Override 382 protected void onDetachedFromWindow() { 383 removeCallbacks(mEndScrollRunnable); 384 super.onDetachedFromWindow(); 385 } 386 387 private void setScrollState(int newState) { 388 if (mScrollState == newState) { 389 return; 390 } 391 392 mScrollState = newState; 393 if (mPageTransformer != null) { 394 // PageTransformers can do complex things that benefit from hardware layers. 395 enableLayers(newState != SCROLL_STATE_IDLE); 396 } 397 if (mOnPageChangeListener != null) { 398 mOnPageChangeListener.onPageScrollStateChanged(newState); 399 } 400 } 401 402 /** 403 * Set a PagerAdapter that will supply views for this pager as needed. 404 * 405 * @param adapter Adapter to use 406 */ 407 public void setAdapter(PagerAdapter adapter) { 408 if (mAdapter != null) { 409 mAdapter.unregisterDataSetObserver(mObserver); 410 mAdapter.startUpdate(this); 411 for (int i = 0; i < mItems.size(); i++) { 412 final ItemInfo ii = mItems.get(i); 413 mAdapter.destroyItem(this, ii.position, ii.object); 414 } 415 mAdapter.finishUpdate(this); 416 mItems.clear(); 417 removeNonDecorViews(); 418 mCurItem = 0; 419 scrollTo(0, 0); 420 } 421 422 final PagerAdapter oldAdapter = mAdapter; 423 mAdapter = adapter; 424 mExpectedAdapterCount = 0; 425 426 if (mAdapter != null) { 427 if (mObserver == null) { 428 mObserver = new PagerObserver(); 429 } 430 mAdapter.registerDataSetObserver(mObserver); 431 mPopulatePending = false; 432 final boolean wasFirstLayout = mFirstLayout; 433 mFirstLayout = true; 434 mExpectedAdapterCount = mAdapter.getCount(); 435 if (mRestoredCurItem >= 0) { 436 mAdapter.restoreState(mRestoredAdapterState, mRestoredClassLoader); 437 setCurrentItemInternal(mRestoredCurItem, false, true); 438 mRestoredCurItem = -1; 439 mRestoredAdapterState = null; 440 mRestoredClassLoader = null; 441 } else if (!wasFirstLayout) { 442 populate(); 443 } else { 444 requestLayout(); 445 } 446 } 447 448 if (mAdapterChangeListener != null && oldAdapter != adapter) { 449 mAdapterChangeListener.onAdapterChanged(oldAdapter, adapter); 450 } 451 } 452 453 private void removeNonDecorViews() { 454 for (int i = 0; i < getChildCount(); i++) { 455 final View child = getChildAt(i); 456 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 457 if (!lp.isDecor) { 458 removeViewAt(i); 459 i--; 460 } 461 } 462 } 463 464 /** 465 * Retrieve the current adapter supplying pages. 466 * 467 * @return The currently registered PagerAdapter 468 */ 469 public PagerAdapter getAdapter() { 470 return mAdapter; 471 } 472 473 void setOnAdapterChangeListener(OnAdapterChangeListener listener) { 474 mAdapterChangeListener = listener; 475 } 476 477 private int getClientWidth() { 478 return getMeasuredWidth() - getPaddingLeft() - getPaddingRight(); 479 } 480 481 /** 482 * Set the currently selected page. If the ViewPager has already been through its first 483 * layout with its current adapter there will be a smooth animated transition between 484 * the current item and the specified item. 485 * 486 * @param item Item index to select 487 */ 488 public void setCurrentItem(int item) { 489 mPopulatePending = false; 490 setCurrentItemInternal(item, !mFirstLayout, false); 491 } 492 493 /** 494 * Set the currently selected page. 495 * 496 * @param item Item index to select 497 * @param smoothScroll True to smoothly scroll to the new item, false to transition immediately 498 */ 499 public void setCurrentItem(int item, boolean smoothScroll) { 500 mPopulatePending = false; 501 setCurrentItemInternal(item, smoothScroll, false); 502 } 503 504 public int getCurrentItem() { 505 return mCurItem; 506 } 507 508 void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) { 509 setCurrentItemInternal(item, smoothScroll, always, 0); 510 } 511 512 void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) { 513 if (mAdapter == null || mAdapter.getCount() <= 0) { 514 setScrollingCacheEnabled(false); 515 return; 516 } 517 if (!always && mCurItem == item && mItems.size() != 0) { 518 setScrollingCacheEnabled(false); 519 return; 520 } 521 522 if (item < 0) { 523 item = 0; 524 } else if (item >= mAdapter.getCount()) { 525 item = mAdapter.getCount() - 1; 526 } 527 final int pageLimit = mOffscreenPageLimit; 528 if (item > (mCurItem + pageLimit) || item < (mCurItem - pageLimit)) { 529 // We are doing a jump by more than one page. To avoid 530 // glitches, we want to keep all current pages in the view 531 // until the scroll ends. 532 for (int i=0; i<mItems.size(); i++) { 533 mItems.get(i).scrolling = true; 534 } 535 } 536 final boolean dispatchSelected = mCurItem != item; 537 538 if (mFirstLayout) { 539 // We don't have any idea how big we are yet and shouldn't have any pages either. 540 // Just set things up and let the pending layout handle things. 541 mCurItem = item; 542 if (dispatchSelected && mOnPageChangeListener != null) { 543 mOnPageChangeListener.onPageSelected(item); 544 } 545 if (dispatchSelected && mInternalPageChangeListener != null) { 546 mInternalPageChangeListener.onPageSelected(item); 547 } 548 requestLayout(); 549 } else { 550 populate(item); 551 scrollToItem(item, smoothScroll, velocity, dispatchSelected); 552 } 553 } 554 555 private void scrollToItem(int item, boolean smoothScroll, int velocity, 556 boolean dispatchSelected) { 557 final ItemInfo curInfo = infoForPosition(item); 558 int destX = 0; 559 if (curInfo != null) { 560 final int width = getClientWidth(); 561 destX = (int) (width * Math.max(mFirstOffset, 562 Math.min(curInfo.offset, mLastOffset))); 563 } 564 if (smoothScroll) { 565 smoothScrollTo(destX, 0, velocity); 566 if (dispatchSelected && mOnPageChangeListener != null) { 567 mOnPageChangeListener.onPageSelected(item); 568 } 569 if (dispatchSelected && mInternalPageChangeListener != null) { 570 mInternalPageChangeListener.onPageSelected(item); 571 } 572 } else { 573 if (dispatchSelected && mOnPageChangeListener != null) { 574 mOnPageChangeListener.onPageSelected(item); 575 } 576 if (dispatchSelected && mInternalPageChangeListener != null) { 577 mInternalPageChangeListener.onPageSelected(item); 578 } 579 completeScroll(false); 580 scrollTo(destX, 0); 581 } 582 } 583 584 /** 585 * Set a listener that will be invoked whenever the page changes or is incrementally 586 * scrolled. See {@link OnPageChangeListener}. 587 * 588 * @param listener Listener to set 589 */ 590 public void setOnPageChangeListener(OnPageChangeListener listener) { 591 mOnPageChangeListener = listener; 592 } 593 594 /** 595 * Set a {@link PageTransformer} that will be called for each attached page whenever 596 * the scroll position is changed. This allows the application to apply custom property 597 * transformations to each page, overriding the default sliding look and feel. 598 * 599 * <p><em>Note:</em> Prior to Android 3.0 the property animation APIs did not exist. 600 * As a result, setting a PageTransformer prior to Android 3.0 (API 11) will have no effect.</p> 601 * 602 * @param reverseDrawingOrder true if the supplied PageTransformer requires page views 603 * to be drawn from last to first instead of first to last. 604 * @param transformer PageTransformer that will modify each page's animation properties 605 */ 606 public void setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer) { 607 if (Build.VERSION.SDK_INT >= 11) { 608 final boolean hasTransformer = transformer != null; 609 final boolean needsPopulate = hasTransformer != (mPageTransformer != null); 610 mPageTransformer = transformer; 611 setChildrenDrawingOrderEnabledCompat(hasTransformer); 612 if (hasTransformer) { 613 mDrawingOrder = reverseDrawingOrder ? DRAW_ORDER_REVERSE : DRAW_ORDER_FORWARD; 614 } else { 615 mDrawingOrder = DRAW_ORDER_DEFAULT; 616 } 617 if (needsPopulate) populate(); 618 } 619 } 620 621 void setChildrenDrawingOrderEnabledCompat(boolean enable) { 622 if (Build.VERSION.SDK_INT >= 7) { 623 if (mSetChildrenDrawingOrderEnabled == null) { 624 try { 625 mSetChildrenDrawingOrderEnabled = ViewGroup.class.getDeclaredMethod( 626 "setChildrenDrawingOrderEnabled", new Class[] { Boolean.TYPE }); 627 } catch (NoSuchMethodException e) { 628 Log.e(TAG, "Can't find setChildrenDrawingOrderEnabled", e); 629 } 630 } 631 try { 632 mSetChildrenDrawingOrderEnabled.invoke(this, enable); 633 } catch (Exception e) { 634 Log.e(TAG, "Error changing children drawing order", e); 635 } 636 } 637 } 638 639 @Override 640 protected int getChildDrawingOrder(int childCount, int i) { 641 final int index = mDrawingOrder == DRAW_ORDER_REVERSE ? childCount - 1 - i : i; 642 final int result = ((LayoutParams) mDrawingOrderedChildren.get(index).getLayoutParams()).childIndex; 643 return result; 644 } 645 646 /** 647 * Set a separate OnPageChangeListener for internal use by the support library. 648 * 649 * @param listener Listener to set 650 * @return The old listener that was set, if any. 651 */ 652 OnPageChangeListener setInternalPageChangeListener(OnPageChangeListener listener) { 653 OnPageChangeListener oldListener = mInternalPageChangeListener; 654 mInternalPageChangeListener = listener; 655 return oldListener; 656 } 657 658 /** 659 * Returns the number of pages that will be retained to either side of the 660 * current page in the view hierarchy in an idle state. Defaults to 1. 661 * 662 * @return How many pages will be kept offscreen on either side 663 * @see #setOffscreenPageLimit(int) 664 */ 665 public int getOffscreenPageLimit() { 666 return mOffscreenPageLimit; 667 } 668 669 /** 670 * Set the number of pages that should be retained to either side of the 671 * current page in the view hierarchy in an idle state. Pages beyond this 672 * limit will be recreated from the adapter when needed. 673 * 674 * <p>This is offered as an optimization. If you know in advance the number 675 * of pages you will need to support or have lazy-loading mechanisms in place 676 * on your pages, tweaking this setting can have benefits in perceived smoothness 677 * of paging animations and interaction. If you have a small number of pages (3-4) 678 * that you can keep active all at once, less time will be spent in layout for 679 * newly created view subtrees as the user pages back and forth.</p> 680 * 681 * <p>You should keep this limit low, especially if your pages have complex layouts. 682 * This setting defaults to 1.</p> 683 * 684 * @param limit How many pages will be kept offscreen in an idle state. 685 */ 686 public void setOffscreenPageLimit(int limit) { 687 if (limit < DEFAULT_OFFSCREEN_PAGES) { 688 Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " + 689 DEFAULT_OFFSCREEN_PAGES); 690 limit = DEFAULT_OFFSCREEN_PAGES; 691 } 692 if (limit != mOffscreenPageLimit) { 693 mOffscreenPageLimit = limit; 694 populate(); 695 } 696 } 697 698 /** 699 * Set the margin between pages. 700 * 701 * @param marginPixels Distance between adjacent pages in pixels 702 * @see #getPageMargin() 703 * @see #setPageMarginDrawable(Drawable) 704 * @see #setPageMarginDrawable(int) 705 */ 706 public void setPageMargin(int marginPixels) { 707 final int oldMargin = mPageMargin; 708 mPageMargin = marginPixels; 709 710 final int width = getWidth(); 711 recomputeScrollPosition(width, width, marginPixels, oldMargin); 712 713 requestLayout(); 714 } 715 716 /** 717 * Return the margin between pages. 718 * 719 * @return The size of the margin in pixels 720 */ 721 public int getPageMargin() { 722 return mPageMargin; 723 } 724 725 /** 726 * Set a drawable that will be used to fill the margin between pages. 727 * 728 * @param d Drawable to display between pages 729 */ 730 public void setPageMarginDrawable(Drawable d) { 731 mMarginDrawable = d; 732 if (d != null) refreshDrawableState(); 733 setWillNotDraw(d == null); 734 invalidate(); 735 } 736 737 /** 738 * Set a drawable that will be used to fill the margin between pages. 739 * 740 * @param resId Resource ID of a drawable to display between pages 741 */ 742 public void setPageMarginDrawable(int resId) { 743 setPageMarginDrawable(getContext().getResources().getDrawable(resId)); 744 } 745 746 @Override 747 protected boolean verifyDrawable(Drawable who) { 748 return super.verifyDrawable(who) || who == mMarginDrawable; 749 } 750 751 @Override 752 protected void drawableStateChanged() { 753 super.drawableStateChanged(); 754 final Drawable d = mMarginDrawable; 755 if (d != null && d.isStateful()) { 756 d.setState(getDrawableState()); 757 } 758 } 759 760 // We want the duration of the page snap animation to be influenced by the distance that 761 // the screen has to travel, however, we don't want this duration to be effected in a 762 // purely linear fashion. Instead, we use this method to moderate the effect that the distance 763 // of travel has on the overall snap duration. 764 float distanceInfluenceForSnapDuration(float f) { 765 f -= 0.5f; // center the values about 0. 766 f *= 0.3f * Math.PI / 2.0f; 767 return (float) Math.sin(f); 768 } 769 770 /** 771 * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. 772 * 773 * @param x the number of pixels to scroll by on the X axis 774 * @param y the number of pixels to scroll by on the Y axis 775 */ 776 void smoothScrollTo(int x, int y) { 777 smoothScrollTo(x, y, 0); 778 } 779 780 /** 781 * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. 782 * 783 * @param x the number of pixels to scroll by on the X axis 784 * @param y the number of pixels to scroll by on the Y axis 785 * @param velocity the velocity associated with a fling, if applicable. (0 otherwise) 786 */ 787 void smoothScrollTo(int x, int y, int velocity) { 788 if (getChildCount() == 0) { 789 // Nothing to do. 790 setScrollingCacheEnabled(false); 791 return; 792 } 793 int sx = getScrollX(); 794 int sy = getScrollY(); 795 int dx = x - sx; 796 int dy = y - sy; 797 if (dx == 0 && dy == 0) { 798 completeScroll(false); 799 populate(); 800 setScrollState(SCROLL_STATE_IDLE); 801 return; 802 } 803 804 setScrollingCacheEnabled(true); 805 setScrollState(SCROLL_STATE_SETTLING); 806 807 final int width = getClientWidth(); 808 final int halfWidth = width / 2; 809 final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width); 810 final float distance = halfWidth + halfWidth * 811 distanceInfluenceForSnapDuration(distanceRatio); 812 813 int duration = 0; 814 velocity = Math.abs(velocity); 815 if (velocity > 0) { 816 duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); 817 } else { 818 final float pageWidth = width * mAdapter.getPageWidth(mCurItem); 819 final float pageDelta = (float) Math.abs(dx) / (pageWidth + mPageMargin); 820 duration = (int) ((pageDelta + 1) * 100); 821 } 822 duration = Math.min(duration, MAX_SETTLE_DURATION); 823 824 mScroller.startScroll(sx, sy, dx, dy, duration); 825 ViewCompat.postInvalidateOnAnimation(this); 826 } 827 828 ItemInfo addNewItem(int position, int index) { 829 ItemInfo ii = new ItemInfo(); 830 ii.position = position; 831 ii.object = mAdapter.instantiateItem(this, position); 832 ii.widthFactor = mAdapter.getPageWidth(position); 833 if (index < 0 || index >= mItems.size()) { 834 mItems.add(ii); 835 } else { 836 mItems.add(index, ii); 837 } 838 return ii; 839 } 840 841 void dataSetChanged() { 842 // This method only gets called if our observer is attached, so mAdapter is non-null. 843 844 final int adapterCount = mAdapter.getCount(); 845 mExpectedAdapterCount = adapterCount; 846 boolean needPopulate = mItems.size() < mOffscreenPageLimit * 2 + 1 && 847 mItems.size() < adapterCount; 848 int newCurrItem = mCurItem; 849 850 boolean isUpdating = false; 851 for (int i = 0; i < mItems.size(); i++) { 852 final ItemInfo ii = mItems.get(i); 853 final int newPos = mAdapter.getItemPosition(ii.object); 854 855 if (newPos == PagerAdapter.POSITION_UNCHANGED) { 856 continue; 857 } 858 859 if (newPos == PagerAdapter.POSITION_NONE) { 860 mItems.remove(i); 861 i--; 862 863 if (!isUpdating) { 864 mAdapter.startUpdate(this); 865 isUpdating = true; 866 } 867 868 mAdapter.destroyItem(this, ii.position, ii.object); 869 needPopulate = true; 870 871 if (mCurItem == ii.position) { 872 // Keep the current item in the valid range 873 newCurrItem = Math.max(0, Math.min(mCurItem, adapterCount - 1)); 874 needPopulate = true; 875 } 876 continue; 877 } 878 879 if (ii.position != newPos) { 880 if (ii.position == mCurItem) { 881 // Our current item changed position. Follow it. 882 newCurrItem = newPos; 883 } 884 885 ii.position = newPos; 886 needPopulate = true; 887 } 888 } 889 890 if (isUpdating) { 891 mAdapter.finishUpdate(this); 892 } 893 894 Collections.sort(mItems, COMPARATOR); 895 896 if (needPopulate) { 897 // Reset our known page widths; populate will recompute them. 898 final int childCount = getChildCount(); 899 for (int i = 0; i < childCount; i++) { 900 final View child = getChildAt(i); 901 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 902 if (!lp.isDecor) { 903 lp.widthFactor = 0.f; 904 } 905 } 906 907 setCurrentItemInternal(newCurrItem, false, true); 908 requestLayout(); 909 } 910 } 911 912 void populate() { 913 populate(mCurItem); 914 } 915 916 void populate(int newCurrentItem) { 917 ItemInfo oldCurInfo = null; 918 int focusDirection = View.FOCUS_FORWARD; 919 if (mCurItem != newCurrentItem) { 920 focusDirection = mCurItem < newCurrentItem ? View.FOCUS_RIGHT : View.FOCUS_LEFT; 921 oldCurInfo = infoForPosition(mCurItem); 922 mCurItem = newCurrentItem; 923 } 924 925 if (mAdapter == null) { 926 sortChildDrawingOrder(); 927 return; 928 } 929 930 // Bail now if we are waiting to populate. This is to hold off 931 // on creating views from the time the user releases their finger to 932 // fling to a new position until we have finished the scroll to 933 // that position, avoiding glitches from happening at that point. 934 if (mPopulatePending) { 935 if (DEBUG) Log.i(TAG, "populate is pending, skipping for now..."); 936 sortChildDrawingOrder(); 937 return; 938 } 939 940 // Also, don't populate until we are attached to a window. This is to 941 // avoid trying to populate before we have restored our view hierarchy 942 // state and conflicting with what is restored. 943 if (getWindowToken() == null) { 944 return; 945 } 946 947 mAdapter.startUpdate(this); 948 949 final int pageLimit = mOffscreenPageLimit; 950 final int startPos = Math.max(0, mCurItem - pageLimit); 951 final int N = mAdapter.getCount(); 952 final int endPos = Math.min(N-1, mCurItem + pageLimit); 953 954 if (N != mExpectedAdapterCount) { 955 String resName; 956 try { 957 resName = getResources().getResourceName(getId()); 958 } catch (Resources.NotFoundException e) { 959 resName = Integer.toHexString(getId()); 960 } 961 throw new IllegalStateException("The application's PagerAdapter changed the adapter's" + 962 " contents without calling PagerAdapter#notifyDataSetChanged!" + 963 " Expected adapter item count: " + mExpectedAdapterCount + ", found: " + N + 964 " Pager id: " + resName + 965 " Pager class: " + getClass() + 966 " Problematic adapter: " + mAdapter.getClass()); 967 } 968 969 // Locate the currently focused item or add it if needed. 970 int curIndex = -1; 971 ItemInfo curItem = null; 972 for (curIndex = 0; curIndex < mItems.size(); curIndex++) { 973 final ItemInfo ii = mItems.get(curIndex); 974 if (ii.position >= mCurItem) { 975 if (ii.position == mCurItem) curItem = ii; 976 break; 977 } 978 } 979 980 if (curItem == null && N > 0) { 981 curItem = addNewItem(mCurItem, curIndex); 982 } 983 984 // Fill 3x the available width or up to the number of offscreen 985 // pages requested to either side, whichever is larger. 986 // If we have no current item we have no work to do. 987 if (curItem != null) { 988 float extraWidthLeft = 0.f; 989 int itemIndex = curIndex - 1; 990 ItemInfo ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; 991 final float leftWidthNeeded = 2.f - curItem.widthFactor + 992 (float) getPaddingLeft() / (float) getClientWidth(); 993 for (int pos = mCurItem - 1; pos >= 0; pos--) { 994 if (extraWidthLeft >= leftWidthNeeded && pos < startPos) { 995 if (ii == null) { 996 break; 997 } 998 if (pos == ii.position && !ii.scrolling) { 999 mItems.remove(itemIndex); 1000 mAdapter.destroyItem(this, pos, ii.object); 1001 if (DEBUG) { 1002 Log.i(TAG, "populate() - destroyItem() with pos: " + pos + 1003 " view: " + ((View) ii.object)); 1004 } 1005 itemIndex--; 1006 curIndex--; 1007 ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; 1008 } 1009 } else if (ii != null && pos == ii.position) { 1010 extraWidthLeft += ii.widthFactor; 1011 itemIndex--; 1012 ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; 1013 } else { 1014 ii = addNewItem(pos, itemIndex + 1); 1015 extraWidthLeft += ii.widthFactor; 1016 curIndex++; 1017 ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; 1018 } 1019 } 1020 1021 float extraWidthRight = curItem.widthFactor; 1022 itemIndex = curIndex + 1; 1023 if (extraWidthRight < 2.f) { 1024 ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; 1025 final float rightWidthNeeded = (float) getPaddingRight() / (float) getClientWidth() 1026 + 2.f; 1027 for (int pos = mCurItem + 1; pos < N; pos++) { 1028 if (extraWidthRight >= rightWidthNeeded && pos > endPos) { 1029 if (ii == null) { 1030 break; 1031 } 1032 if (pos == ii.position && !ii.scrolling) { 1033 mItems.remove(itemIndex); 1034 mAdapter.destroyItem(this, pos, ii.object); 1035 if (DEBUG) { 1036 Log.i(TAG, "populate() - destroyItem() with pos: " + pos + 1037 " view: " + ((View) ii.object)); 1038 } 1039 ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; 1040 } 1041 } else if (ii != null && pos == ii.position) { 1042 extraWidthRight += ii.widthFactor; 1043 itemIndex++; 1044 ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; 1045 } else { 1046 ii = addNewItem(pos, itemIndex); 1047 itemIndex++; 1048 extraWidthRight += ii.widthFactor; 1049 ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; 1050 } 1051 } 1052 } 1053 1054 calculatePageOffsets(curItem, curIndex, oldCurInfo); 1055 } 1056 1057 if (DEBUG) { 1058 Log.i(TAG, "Current page list:"); 1059 for (int i=0; i<mItems.size(); i++) { 1060 Log.i(TAG, "#" + i + ": page " + mItems.get(i).position); 1061 } 1062 } 1063 1064 mAdapter.setPrimaryItem(this, mCurItem, curItem != null ? curItem.object : null); 1065 1066 mAdapter.finishUpdate(this); 1067 1068 // Check width measurement of current pages and drawing sort order. 1069 // Update LayoutParams as needed. 1070 final int childCount = getChildCount(); 1071 for (int i = 0; i < childCount; i++) { 1072 final View child = getChildAt(i); 1073 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 1074 lp.childIndex = i; 1075 if (!lp.isDecor && lp.widthFactor == 0.f) { 1076 // 0 means requery the adapter for this, it doesn't have a valid width. 1077 final ItemInfo ii = infoForChild(child); 1078 if (ii != null) { 1079 lp.widthFactor = ii.widthFactor; 1080 lp.position = ii.position; 1081 } 1082 } 1083 } 1084 sortChildDrawingOrder(); 1085 1086 if (hasFocus()) { 1087 View currentFocused = findFocus(); 1088 ItemInfo ii = currentFocused != null ? infoForAnyChild(currentFocused) : null; 1089 if (ii == null || ii.position != mCurItem) { 1090 for (int i=0; i<getChildCount(); i++) { 1091 View child = getChildAt(i); 1092 ii = infoForChild(child); 1093 if (ii != null && ii.position == mCurItem) { 1094 if (child.requestFocus(focusDirection)) { 1095 break; 1096 } 1097 } 1098 } 1099 } 1100 } 1101 } 1102 1103 private void sortChildDrawingOrder() { 1104 if (mDrawingOrder != DRAW_ORDER_DEFAULT) { 1105 if (mDrawingOrderedChildren == null) { 1106 mDrawingOrderedChildren = new ArrayList<View>(); 1107 } else { 1108 mDrawingOrderedChildren.clear(); 1109 } 1110 final int childCount = getChildCount(); 1111 for (int i = 0; i < childCount; i++) { 1112 final View child = getChildAt(i); 1113 mDrawingOrderedChildren.add(child); 1114 } 1115 Collections.sort(mDrawingOrderedChildren, sPositionComparator); 1116 } 1117 } 1118 1119 private void calculatePageOffsets(ItemInfo curItem, int curIndex, ItemInfo oldCurInfo) { 1120 final int N = mAdapter.getCount(); 1121 final int width = getClientWidth(); 1122 final float marginOffset = width > 0 ? (float) mPageMargin / width : 0; 1123 // Fix up offsets for later layout. 1124 if (oldCurInfo != null) { 1125 final int oldCurPosition = oldCurInfo.position; 1126 // Base offsets off of oldCurInfo. 1127 if (oldCurPosition < curItem.position) { 1128 int itemIndex = 0; 1129 ItemInfo ii = null; 1130 float offset = oldCurInfo.offset + oldCurInfo.widthFactor + marginOffset; 1131 for (int pos = oldCurPosition + 1; 1132 pos <= curItem.position && itemIndex < mItems.size(); pos++) { 1133 ii = mItems.get(itemIndex); 1134 while (pos > ii.position && itemIndex < mItems.size() - 1) { 1135 itemIndex++; 1136 ii = mItems.get(itemIndex); 1137 } 1138 while (pos < ii.position) { 1139 // We don't have an item populated for this, 1140 // ask the adapter for an offset. 1141 offset += mAdapter.getPageWidth(pos) + marginOffset; 1142 pos++; 1143 } 1144 ii.offset = offset; 1145 offset += ii.widthFactor + marginOffset; 1146 } 1147 } else if (oldCurPosition > curItem.position) { 1148 int itemIndex = mItems.size() - 1; 1149 ItemInfo ii = null; 1150 float offset = oldCurInfo.offset; 1151 for (int pos = oldCurPosition - 1; 1152 pos >= curItem.position && itemIndex >= 0; pos--) { 1153 ii = mItems.get(itemIndex); 1154 while (pos < ii.position && itemIndex > 0) { 1155 itemIndex--; 1156 ii = mItems.get(itemIndex); 1157 } 1158 while (pos > ii.position) { 1159 // We don't have an item populated for this, 1160 // ask the adapter for an offset. 1161 offset -= mAdapter.getPageWidth(pos) + marginOffset; 1162 pos--; 1163 } 1164 offset -= ii.widthFactor + marginOffset; 1165 ii.offset = offset; 1166 } 1167 } 1168 } 1169 1170 // Base all offsets off of curItem. 1171 final int itemCount = mItems.size(); 1172 float offset = curItem.offset; 1173 int pos = curItem.position - 1; 1174 mFirstOffset = curItem.position == 0 ? curItem.offset : -Float.MAX_VALUE; 1175 mLastOffset = curItem.position == N - 1 ? 1176 curItem.offset + curItem.widthFactor - 1 : Float.MAX_VALUE; 1177 // Previous pages 1178 for (int i = curIndex - 1; i >= 0; i--, pos--) { 1179 final ItemInfo ii = mItems.get(i); 1180 while (pos > ii.position) { 1181 offset -= mAdapter.getPageWidth(pos--) + marginOffset; 1182 } 1183 offset -= ii.widthFactor + marginOffset; 1184 ii.offset = offset; 1185 if (ii.position == 0) mFirstOffset = offset; 1186 } 1187 offset = curItem.offset + curItem.widthFactor + marginOffset; 1188 pos = curItem.position + 1; 1189 // Next pages 1190 for (int i = curIndex + 1; i < itemCount; i++, pos++) { 1191 final ItemInfo ii = mItems.get(i); 1192 while (pos < ii.position) { 1193 offset += mAdapter.getPageWidth(pos++) + marginOffset; 1194 } 1195 if (ii.position == N - 1) { 1196 mLastOffset = offset + ii.widthFactor - 1; 1197 } 1198 ii.offset = offset; 1199 offset += ii.widthFactor + marginOffset; 1200 } 1201 1202 mNeedCalculatePageOffsets = false; 1203 } 1204 1205 /** 1206 * This is the persistent state that is saved by ViewPager. Only needed 1207 * if you are creating a sublass of ViewPager that must save its own 1208 * state, in which case it should implement a subclass of this which 1209 * contains that state. 1210 */ 1211 public static class SavedState extends BaseSavedState { 1212 int position; 1213 Parcelable adapterState; 1214 ClassLoader loader; 1215 1216 public SavedState(Parcelable superState) { 1217 super(superState); 1218 } 1219 1220 @Override 1221 public void writeToParcel(Parcel out, int flags) { 1222 super.writeToParcel(out, flags); 1223 out.writeInt(position); 1224 out.writeParcelable(adapterState, flags); 1225 } 1226 1227 @Override 1228 public String toString() { 1229 return "FragmentPager.SavedState{" 1230 + Integer.toHexString(System.identityHashCode(this)) 1231 + " position=" + position + "}"; 1232 } 1233 1234 public static final Parcelable.Creator<SavedState> CREATOR 1235 = ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks<SavedState>() { 1236 @Override 1237 public SavedState createFromParcel(Parcel in, ClassLoader loader) { 1238 return new SavedState(in, loader); 1239 } 1240 @Override 1241 public SavedState[] newArray(int size) { 1242 return new SavedState[size]; 1243 } 1244 }); 1245 1246 SavedState(Parcel in, ClassLoader loader) { 1247 super(in); 1248 if (loader == null) { 1249 loader = getClass().getClassLoader(); 1250 } 1251 position = in.readInt(); 1252 adapterState = in.readParcelable(loader); 1253 this.loader = loader; 1254 } 1255 } 1256 1257 @Override 1258 public Parcelable onSaveInstanceState() { 1259 Parcelable superState = super.onSaveInstanceState(); 1260 SavedState ss = new SavedState(superState); 1261 ss.position = mCurItem; 1262 if (mAdapter != null) { 1263 ss.adapterState = mAdapter.saveState(); 1264 } 1265 return ss; 1266 } 1267 1268 @Override 1269 public void onRestoreInstanceState(Parcelable state) { 1270 if (!(state instanceof SavedState)) { 1271 super.onRestoreInstanceState(state); 1272 return; 1273 } 1274 1275 SavedState ss = (SavedState)state; 1276 super.onRestoreInstanceState(ss.getSuperState()); 1277 1278 if (mAdapter != null) { 1279 mAdapter.restoreState(ss.adapterState, ss.loader); 1280 setCurrentItemInternal(ss.position, false, true); 1281 } else { 1282 mRestoredCurItem = ss.position; 1283 mRestoredAdapterState = ss.adapterState; 1284 mRestoredClassLoader = ss.loader; 1285 } 1286 } 1287 1288 @Override 1289 public void addView(View child, int index, ViewGroup.LayoutParams params) { 1290 if (!checkLayoutParams(params)) { 1291 params = generateLayoutParams(params); 1292 } 1293 final LayoutParams lp = (LayoutParams) params; 1294 lp.isDecor |= child instanceof Decor; 1295 if (mInLayout) { 1296 if (lp != null && lp.isDecor) { 1297 throw new IllegalStateException("Cannot add pager decor view during layout"); 1298 } 1299 lp.needsMeasure = true; 1300 addViewInLayout(child, index, params); 1301 } else { 1302 super.addView(child, index, params); 1303 } 1304 1305 if (USE_CACHE) { 1306 if (child.getVisibility() != GONE) { 1307 child.setDrawingCacheEnabled(mScrollingCacheEnabled); 1308 } else { 1309 child.setDrawingCacheEnabled(false); 1310 } 1311 } 1312 } 1313 1314 @Override 1315 public void removeView(View view) { 1316 if (mInLayout) { 1317 removeViewInLayout(view); 1318 } else { 1319 super.removeView(view); 1320 } 1321 } 1322 1323 ItemInfo infoForChild(View child) { 1324 for (int i=0; i<mItems.size(); i++) { 1325 ItemInfo ii = mItems.get(i); 1326 if (mAdapter.isViewFromObject(child, ii.object)) { 1327 return ii; 1328 } 1329 } 1330 return null; 1331 } 1332 1333 ItemInfo infoForAnyChild(View child) { 1334 ViewParent parent; 1335 while ((parent=child.getParent()) != this) { 1336 if (parent == null || !(parent instanceof View)) { 1337 return null; 1338 } 1339 child = (View)parent; 1340 } 1341 return infoForChild(child); 1342 } 1343 1344 ItemInfo infoForPosition(int position) { 1345 for (int i = 0; i < mItems.size(); i++) { 1346 ItemInfo ii = mItems.get(i); 1347 if (ii.position == position) { 1348 return ii; 1349 } 1350 } 1351 return null; 1352 } 1353 1354 @Override 1355 protected void onAttachedToWindow() { 1356 super.onAttachedToWindow(); 1357 mFirstLayout = true; 1358 } 1359 1360 @Override 1361 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 1362 // For simple implementation, our internal size is always 0. 1363 // We depend on the container to specify the layout size of 1364 // our view. We can't really know what it is since we will be 1365 // adding and removing different arbitrary views and do not 1366 // want the layout to change as this happens. 1367 setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), 1368 getDefaultSize(0, heightMeasureSpec)); 1369 1370 final int measuredWidth = getMeasuredWidth(); 1371 final int maxGutterSize = measuredWidth / 10; 1372 mGutterSize = Math.min(maxGutterSize, mDefaultGutterSize); 1373 1374 // Children are just made to fill our space. 1375 int childWidthSize = measuredWidth - getPaddingLeft() - getPaddingRight(); 1376 int childHeightSize = getMeasuredHeight() - getPaddingTop() - getPaddingBottom(); 1377 1378 /* 1379 * Make sure all children have been properly measured. Decor views first. 1380 * Right now we cheat and make this less complicated by assuming decor 1381 * views won't intersect. We will pin to edges based on gravity. 1382 */ 1383 int size = getChildCount(); 1384 for (int i = 0; i < size; ++i) { 1385 final View child = getChildAt(i); 1386 if (child.getVisibility() != GONE) { 1387 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 1388 if (lp != null && lp.isDecor) { 1389 final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK; 1390 final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK; 1391 int widthMode = MeasureSpec.AT_MOST; 1392 int heightMode = MeasureSpec.AT_MOST; 1393 boolean consumeVertical = vgrav == Gravity.TOP || vgrav == Gravity.BOTTOM; 1394 boolean consumeHorizontal = hgrav == Gravity.LEFT || hgrav == Gravity.RIGHT; 1395 1396 if (consumeVertical) { 1397 widthMode = MeasureSpec.EXACTLY; 1398 } else if (consumeHorizontal) { 1399 heightMode = MeasureSpec.EXACTLY; 1400 } 1401 1402 int widthSize = childWidthSize; 1403 int heightSize = childHeightSize; 1404 if (lp.width != LayoutParams.WRAP_CONTENT) { 1405 widthMode = MeasureSpec.EXACTLY; 1406 if (lp.width != LayoutParams.FILL_PARENT) { 1407 widthSize = lp.width; 1408 } 1409 } 1410 if (lp.height != LayoutParams.WRAP_CONTENT) { 1411 heightMode = MeasureSpec.EXACTLY; 1412 if (lp.height != LayoutParams.FILL_PARENT) { 1413 heightSize = lp.height; 1414 } 1415 } 1416 final int widthSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode); 1417 final int heightSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode); 1418 child.measure(widthSpec, heightSpec); 1419 1420 if (consumeVertical) { 1421 childHeightSize -= child.getMeasuredHeight(); 1422 } else if (consumeHorizontal) { 1423 childWidthSize -= child.getMeasuredWidth(); 1424 } 1425 } 1426 } 1427 } 1428 1429 mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY); 1430 mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeightSize, MeasureSpec.EXACTLY); 1431 1432 // Make sure we have created all fragments that we need to have shown. 1433 mInLayout = true; 1434 populate(); 1435 mInLayout = false; 1436 1437 // Page views next. 1438 size = getChildCount(); 1439 for (int i = 0; i < size; ++i) { 1440 final View child = getChildAt(i); 1441 if (child.getVisibility() != GONE) { 1442 if (DEBUG) Log.v(TAG, "Measuring #" + i + " " + child 1443 + ": " + mChildWidthMeasureSpec); 1444 1445 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 1446 if (lp == null || !lp.isDecor) { 1447 final int widthSpec = MeasureSpec.makeMeasureSpec( 1448 (int) (childWidthSize * lp.widthFactor), MeasureSpec.EXACTLY); 1449 child.measure(widthSpec, mChildHeightMeasureSpec); 1450 } 1451 } 1452 } 1453 } 1454 1455 @Override 1456 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 1457 super.onSizeChanged(w, h, oldw, oldh); 1458 1459 // Make sure scroll position is set correctly. 1460 if (w != oldw) { 1461 recomputeScrollPosition(w, oldw, mPageMargin, mPageMargin); 1462 } 1463 } 1464 1465 private void recomputeScrollPosition(int width, int oldWidth, int margin, int oldMargin) { 1466 if (oldWidth > 0 && !mItems.isEmpty()) { 1467 final int widthWithMargin = width - getPaddingLeft() - getPaddingRight() + margin; 1468 final int oldWidthWithMargin = oldWidth - getPaddingLeft() - getPaddingRight() 1469 + oldMargin; 1470 final int xpos = getScrollX(); 1471 final float pageOffset = (float) xpos / oldWidthWithMargin; 1472 final int newOffsetPixels = (int) (pageOffset * widthWithMargin); 1473 1474 scrollTo(newOffsetPixels, getScrollY()); 1475 if (!mScroller.isFinished()) { 1476 // We now return to your regularly scheduled scroll, already in progress. 1477 final int newDuration = mScroller.getDuration() - mScroller.timePassed(); 1478 ItemInfo targetInfo = infoForPosition(mCurItem); 1479 mScroller.startScroll(newOffsetPixels, 0, 1480 (int) (targetInfo.offset * width), 0, newDuration); 1481 } 1482 } else { 1483 final ItemInfo ii = infoForPosition(mCurItem); 1484 final float scrollOffset = ii != null ? Math.min(ii.offset, mLastOffset) : 0; 1485 final int scrollPos = (int) (scrollOffset * 1486 (width - getPaddingLeft() - getPaddingRight())); 1487 if (scrollPos != getScrollX()) { 1488 completeScroll(false); 1489 scrollTo(scrollPos, getScrollY()); 1490 } 1491 } 1492 } 1493 1494 @Override 1495 protected void onLayout(boolean changed, int l, int t, int r, int b) { 1496 final int count = getChildCount(); 1497 int width = r - l; 1498 int height = b - t; 1499 int paddingLeft = getPaddingLeft(); 1500 int paddingTop = getPaddingTop(); 1501 int paddingRight = getPaddingRight(); 1502 int paddingBottom = getPaddingBottom(); 1503 final int scrollX = getScrollX(); 1504 1505 int decorCount = 0; 1506 1507 // First pass - decor views. We need to do this in two passes so that 1508 // we have the proper offsets for non-decor views later. 1509 for (int i = 0; i < count; i++) { 1510 final View child = getChildAt(i); 1511 if (child.getVisibility() != GONE) { 1512 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 1513 int childLeft = 0; 1514 int childTop = 0; 1515 if (lp.isDecor) { 1516 final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK; 1517 final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK; 1518 switch (hgrav) { 1519 default: 1520 childLeft = paddingLeft; 1521 break; 1522 case Gravity.LEFT: 1523 childLeft = paddingLeft; 1524 paddingLeft += child.getMeasuredWidth(); 1525 break; 1526 case Gravity.CENTER_HORIZONTAL: 1527 childLeft = Math.max((width - child.getMeasuredWidth()) / 2, 1528 paddingLeft); 1529 break; 1530 case Gravity.RIGHT: 1531 childLeft = width - paddingRight - child.getMeasuredWidth(); 1532 paddingRight += child.getMeasuredWidth(); 1533 break; 1534 } 1535 switch (vgrav) { 1536 default: 1537 childTop = paddingTop; 1538 break; 1539 case Gravity.TOP: 1540 childTop = paddingTop; 1541 paddingTop += child.getMeasuredHeight(); 1542 break; 1543 case Gravity.CENTER_VERTICAL: 1544 childTop = Math.max((height - child.getMeasuredHeight()) / 2, 1545 paddingTop); 1546 break; 1547 case Gravity.BOTTOM: 1548 childTop = height - paddingBottom - child.getMeasuredHeight(); 1549 paddingBottom += child.getMeasuredHeight(); 1550 break; 1551 } 1552 childLeft += scrollX; 1553 child.layout(childLeft, childTop, 1554 childLeft + child.getMeasuredWidth(), 1555 childTop + child.getMeasuredHeight()); 1556 decorCount++; 1557 } 1558 } 1559 } 1560 1561 final int childWidth = width - paddingLeft - paddingRight; 1562 // Page views. Do this once we have the right padding offsets from above. 1563 for (int i = 0; i < count; i++) { 1564 final View child = getChildAt(i); 1565 if (child.getVisibility() != GONE) { 1566 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 1567 ItemInfo ii; 1568 if (!lp.isDecor && (ii = infoForChild(child)) != null) { 1569 int loff = (int) (childWidth * ii.offset); 1570 int childLeft = paddingLeft + loff; 1571 int childTop = paddingTop; 1572 if (lp.needsMeasure) { 1573 // This was added during layout and needs measurement. 1574 // Do it now that we know what we're working with. 1575 lp.needsMeasure = false; 1576 final int widthSpec = MeasureSpec.makeMeasureSpec( 1577 (int) (childWidth * lp.widthFactor), 1578 MeasureSpec.EXACTLY); 1579 final int heightSpec = MeasureSpec.makeMeasureSpec( 1580 (int) (height - paddingTop - paddingBottom), 1581 MeasureSpec.EXACTLY); 1582 child.measure(widthSpec, heightSpec); 1583 } 1584 if (DEBUG) Log.v(TAG, "Positioning #" + i + " " + child + " f=" + ii.object 1585 + ":" + childLeft + "," + childTop + " " + child.getMeasuredWidth() 1586 + "x" + child.getMeasuredHeight()); 1587 child.layout(childLeft, childTop, 1588 childLeft + child.getMeasuredWidth(), 1589 childTop + child.getMeasuredHeight()); 1590 } 1591 } 1592 } 1593 mTopPageBounds = paddingTop; 1594 mBottomPageBounds = height - paddingBottom; 1595 mDecorChildCount = decorCount; 1596 1597 if (mFirstLayout) { 1598 scrollToItem(mCurItem, false, 0, false); 1599 } 1600 mFirstLayout = false; 1601 } 1602 1603 @Override 1604 public void computeScroll() { 1605 if (!mScroller.isFinished() && mScroller.computeScrollOffset()) { 1606 int oldX = getScrollX(); 1607 int oldY = getScrollY(); 1608 int x = mScroller.getCurrX(); 1609 int y = mScroller.getCurrY(); 1610 1611 if (oldX != x || oldY != y) { 1612 scrollTo(x, y); 1613 if (!pageScrolled(x)) { 1614 mScroller.abortAnimation(); 1615 scrollTo(0, y); 1616 } 1617 } 1618 1619 // Keep on drawing until the animation has finished. 1620 ViewCompat.postInvalidateOnAnimation(this); 1621 return; 1622 } 1623 1624 // Done with scroll, clean up state. 1625 completeScroll(true); 1626 } 1627 1628 private boolean pageScrolled(int xpos) { 1629 if (mItems.size() == 0) { 1630 mCalledSuper = false; 1631 onPageScrolled(0, 0, 0); 1632 if (!mCalledSuper) { 1633 throw new IllegalStateException( 1634 "onPageScrolled did not call superclass implementation"); 1635 } 1636 return false; 1637 } 1638 final ItemInfo ii = infoForCurrentScrollPosition(); 1639 final int width = getClientWidth(); 1640 final int widthWithMargin = width + mPageMargin; 1641 final float marginOffset = (float) mPageMargin / width; 1642 final int currentPage = ii.position; 1643 final float pageOffset = (((float) xpos / width) - ii.offset) / 1644 (ii.widthFactor + marginOffset); 1645 final int offsetPixels = (int) (pageOffset * widthWithMargin); 1646 1647 mCalledSuper = false; 1648 onPageScrolled(currentPage, pageOffset, offsetPixels); 1649 if (!mCalledSuper) { 1650 throw new IllegalStateException( 1651 "onPageScrolled did not call superclass implementation"); 1652 } 1653 return true; 1654 } 1655 1656 /** 1657 * This method will be invoked when the current page is scrolled, either as part 1658 * of a programmatically initiated smooth scroll or a user initiated touch scroll. 1659 * If you override this method you must call through to the superclass implementation 1660 * (e.g. super.onPageScrolled(position, offset, offsetPixels)) before onPageScrolled 1661 * returns. 1662 * 1663 * @param position Position index of the first page currently being displayed. 1664 * Page position+1 will be visible if positionOffset is nonzero. 1665 * @param offset Value from [0, 1) indicating the offset from the page at position. 1666 * @param offsetPixels Value in pixels indicating the offset from position. 1667 */ 1668 protected void onPageScrolled(int position, float offset, int offsetPixels) { 1669 // Offset any decor views if needed - keep them on-screen at all times. 1670 if (mDecorChildCount > 0) { 1671 final int scrollX = getScrollX(); 1672 int paddingLeft = getPaddingLeft(); 1673 int paddingRight = getPaddingRight(); 1674 final int width = getWidth(); 1675 final int childCount = getChildCount(); 1676 for (int i = 0; i < childCount; i++) { 1677 final View child = getChildAt(i); 1678 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 1679 if (!lp.isDecor) continue; 1680 1681 final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK; 1682 int childLeft = 0; 1683 switch (hgrav) { 1684 default: 1685 childLeft = paddingLeft; 1686 break; 1687 case Gravity.LEFT: 1688 childLeft = paddingLeft; 1689 paddingLeft += child.getWidth(); 1690 break; 1691 case Gravity.CENTER_HORIZONTAL: 1692 childLeft = Math.max((width - child.getMeasuredWidth()) / 2, 1693 paddingLeft); 1694 break; 1695 case Gravity.RIGHT: 1696 childLeft = width - paddingRight - child.getMeasuredWidth(); 1697 paddingRight += child.getMeasuredWidth(); 1698 break; 1699 } 1700 childLeft += scrollX; 1701 1702 final int childOffset = childLeft - child.getLeft(); 1703 if (childOffset != 0) { 1704 child.offsetLeftAndRight(childOffset); 1705 } 1706 } 1707 } 1708 1709 if (mOnPageChangeListener != null) { 1710 mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels); 1711 } 1712 if (mInternalPageChangeListener != null) { 1713 mInternalPageChangeListener.onPageScrolled(position, offset, offsetPixels); 1714 } 1715 1716 if (mPageTransformer != null) { 1717 final int scrollX = getScrollX(); 1718 final int childCount = getChildCount(); 1719 for (int i = 0; i < childCount; i++) { 1720 final View child = getChildAt(i); 1721 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 1722 1723 if (lp.isDecor) continue; 1724 1725 final float transformPos = (float) (child.getLeft() - scrollX) / getClientWidth(); 1726 mPageTransformer.transformPage(child, transformPos); 1727 } 1728 } 1729 1730 mCalledSuper = true; 1731 } 1732 1733 private void completeScroll(boolean postEvents) { 1734 boolean needPopulate = mScrollState == SCROLL_STATE_SETTLING; 1735 if (needPopulate) { 1736 // Done with scroll, no longer want to cache view drawing. 1737 setScrollingCacheEnabled(false); 1738 mScroller.abortAnimation(); 1739 int oldX = getScrollX(); 1740 int oldY = getScrollY(); 1741 int x = mScroller.getCurrX(); 1742 int y = mScroller.getCurrY(); 1743 if (oldX != x || oldY != y) { 1744 scrollTo(x, y); 1745 } 1746 } 1747 mPopulatePending = false; 1748 for (int i=0; i<mItems.size(); i++) { 1749 ItemInfo ii = mItems.get(i); 1750 if (ii.scrolling) { 1751 needPopulate = true; 1752 ii.scrolling = false; 1753 } 1754 } 1755 if (needPopulate) { 1756 if (postEvents) { 1757 ViewCompat.postOnAnimation(this, mEndScrollRunnable); 1758 } else { 1759 mEndScrollRunnable.run(); 1760 } 1761 } 1762 } 1763 1764 private boolean isGutterDrag(float x, float dx) { 1765 return (x < mGutterSize && dx > 0) || (x > getWidth() - mGutterSize && dx < 0); 1766 } 1767 1768 private void enableLayers(boolean enable) { 1769 final int childCount = getChildCount(); 1770 for (int i = 0; i < childCount; i++) { 1771 final int layerType = enable ? 1772 ViewCompat.LAYER_TYPE_HARDWARE : ViewCompat.LAYER_TYPE_NONE; 1773 ViewCompat.setLayerType(getChildAt(i), layerType, null); 1774 } 1775 } 1776 1777 @Override 1778 public boolean onInterceptTouchEvent(MotionEvent ev) { 1779 /* 1780 * This method JUST determines whether we want to intercept the motion. 1781 * If we return true, onMotionEvent will be called and we do the actual 1782 * scrolling there. 1783 */ 1784 1785 final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; 1786 1787 // Always take care of the touch gesture being complete. 1788 if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { 1789 // Release the drag. 1790 if (DEBUG) Log.v(TAG, "Intercept done!"); 1791 mIsBeingDragged = false; 1792 mIsUnableToDrag = false; 1793 mActivePointerId = INVALID_POINTER; 1794 if (mVelocityTracker != null) { 1795 mVelocityTracker.recycle(); 1796 mVelocityTracker = null; 1797 } 1798 return false; 1799 } 1800 1801 // Nothing more to do here if we have decided whether or not we 1802 // are dragging. 1803 if (action != MotionEvent.ACTION_DOWN) { 1804 if (mIsBeingDragged) { 1805 if (DEBUG) Log.v(TAG, "Intercept returning true!"); 1806 return true; 1807 } 1808 if (mIsUnableToDrag) { 1809 if (DEBUG) Log.v(TAG, "Intercept returning false!"); 1810 return false; 1811 } 1812 } 1813 1814 switch (action) { 1815 case MotionEvent.ACTION_MOVE: { 1816 /* 1817 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check 1818 * whether the user has moved far enough from his original down touch. 1819 */ 1820 1821 /* 1822 * Locally do absolute value. mLastMotionY is set to the y value 1823 * of the down event. 1824 */ 1825 final int activePointerId = mActivePointerId; 1826 if (activePointerId == INVALID_POINTER) { 1827 // If we don't have a valid id, the touch down wasn't on content. 1828 break; 1829 } 1830 1831 final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId); 1832 final float x = MotionEventCompat.getX(ev, pointerIndex); 1833 final float dx = x - mLastMotionX; 1834 final float xDiff = Math.abs(dx); 1835 final float y = MotionEventCompat.getY(ev, pointerIndex); 1836 final float yDiff = Math.abs(y - mInitialMotionY); 1837 if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); 1838 1839 if (dx != 0 && !isGutterDrag(mLastMotionX, dx) && 1840 canScroll(this, false, (int) dx, (int) x, (int) y)) { 1841 // Nested view has scrollable area under this point. Let it be handled there. 1842 mLastMotionX = x; 1843 mLastMotionY = y; 1844 mIsUnableToDrag = true; 1845 return false; 1846 } 1847 if (xDiff > mTouchSlop && xDiff * 0.5f > yDiff) { 1848 if (DEBUG) Log.v(TAG, "Starting drag!"); 1849 mIsBeingDragged = true; 1850 setScrollState(SCROLL_STATE_DRAGGING); 1851 mLastMotionX = dx > 0 ? mInitialMotionX + mTouchSlop : 1852 mInitialMotionX - mTouchSlop; 1853 mLastMotionY = y; 1854 setScrollingCacheEnabled(true); 1855 } else if (yDiff > mTouchSlop) { 1856 // The finger has moved enough in the vertical 1857 // direction to be counted as a drag... abort 1858 // any attempt to drag horizontally, to work correctly 1859 // with children that have scrolling containers. 1860 if (DEBUG) Log.v(TAG, "Starting unable to drag!"); 1861 mIsUnableToDrag = true; 1862 } 1863 if (mIsBeingDragged) { 1864 // Scroll to follow the motion event 1865 if (performDrag(x)) { 1866 ViewCompat.postInvalidateOnAnimation(this); 1867 } 1868 } 1869 break; 1870 } 1871 1872 case MotionEvent.ACTION_DOWN: { 1873 /* 1874 * Remember location of down touch. 1875 * ACTION_DOWN always refers to pointer index 0. 1876 */ 1877 mLastMotionX = mInitialMotionX = ev.getX(); 1878 mLastMotionY = mInitialMotionY = ev.getY(); 1879 mActivePointerId = MotionEventCompat.getPointerId(ev, 0); 1880 mIsUnableToDrag = false; 1881 1882 mScroller.computeScrollOffset(); 1883 if (mScrollState == SCROLL_STATE_SETTLING && 1884 Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) > mCloseEnough) { 1885 // Let the user 'catch' the pager as it animates. 1886 mScroller.abortAnimation(); 1887 mPopulatePending = false; 1888 populate(); 1889 mIsBeingDragged = true; 1890 setScrollState(SCROLL_STATE_DRAGGING); 1891 } else { 1892 completeScroll(false); 1893 mIsBeingDragged = false; 1894 } 1895 1896 if (DEBUG) Log.v(TAG, "Down at " + mLastMotionX + "," + mLastMotionY 1897 + " mIsBeingDragged=" + mIsBeingDragged 1898 + "mIsUnableToDrag=" + mIsUnableToDrag); 1899 break; 1900 } 1901 1902 case MotionEventCompat.ACTION_POINTER_UP: 1903 onSecondaryPointerUp(ev); 1904 break; 1905 } 1906 1907 if (mVelocityTracker == null) { 1908 mVelocityTracker = VelocityTracker.obtain(); 1909 } 1910 mVelocityTracker.addMovement(ev); 1911 1912 /* 1913 * The only time we want to intercept motion events is if we are in the 1914 * drag mode. 1915 */ 1916 return mIsBeingDragged; 1917 } 1918 1919 @Override 1920 public boolean onTouchEvent(MotionEvent ev) { 1921 if (mFakeDragging) { 1922 // A fake drag is in progress already, ignore this real one 1923 // but still eat the touch events. 1924 // (It is likely that the user is multi-touching the screen.) 1925 return true; 1926 } 1927 1928 if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) { 1929 // Don't handle edge touches immediately -- they may actually belong to one of our 1930 // descendants. 1931 return false; 1932 } 1933 1934 if (mAdapter == null || mAdapter.getCount() == 0) { 1935 // Nothing to present or scroll; nothing to touch. 1936 return false; 1937 } 1938 1939 if (mVelocityTracker == null) { 1940 mVelocityTracker = VelocityTracker.obtain(); 1941 } 1942 mVelocityTracker.addMovement(ev); 1943 1944 final int action = ev.getAction(); 1945 boolean needsInvalidate = false; 1946 1947 switch (action & MotionEventCompat.ACTION_MASK) { 1948 case MotionEvent.ACTION_DOWN: { 1949 mScroller.abortAnimation(); 1950 mPopulatePending = false; 1951 populate(); 1952 mIsBeingDragged = true; 1953 setScrollState(SCROLL_STATE_DRAGGING); 1954 1955 // Remember where the motion event started 1956 mLastMotionX = mInitialMotionX = ev.getX(); 1957 mLastMotionY = mInitialMotionY = ev.getY(); 1958 mActivePointerId = MotionEventCompat.getPointerId(ev, 0); 1959 break; 1960 } 1961 case MotionEvent.ACTION_MOVE: 1962 if (!mIsBeingDragged) { 1963 final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); 1964 final float x = MotionEventCompat.getX(ev, pointerIndex); 1965 final float xDiff = Math.abs(x - mLastMotionX); 1966 final float y = MotionEventCompat.getY(ev, pointerIndex); 1967 final float yDiff = Math.abs(y - mLastMotionY); 1968 if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); 1969 if (xDiff > mTouchSlop && xDiff > yDiff) { 1970 if (DEBUG) Log.v(TAG, "Starting drag!"); 1971 mIsBeingDragged = true; 1972 mLastMotionX = x - mInitialMotionX > 0 ? mInitialMotionX + mTouchSlop : 1973 mInitialMotionX - mTouchSlop; 1974 mLastMotionY = y; 1975 setScrollState(SCROLL_STATE_DRAGGING); 1976 setScrollingCacheEnabled(true); 1977 } 1978 } 1979 // Not else! Note that mIsBeingDragged can be set above. 1980 if (mIsBeingDragged) { 1981 // Scroll to follow the motion event 1982 final int activePointerIndex = MotionEventCompat.findPointerIndex( 1983 ev, mActivePointerId); 1984 final float x = MotionEventCompat.getX(ev, activePointerIndex); 1985 needsInvalidate |= performDrag(x); 1986 } 1987 break; 1988 case MotionEvent.ACTION_UP: 1989 if (mIsBeingDragged) { 1990 final VelocityTracker velocityTracker = mVelocityTracker; 1991 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 1992 int initialVelocity = (int) VelocityTrackerCompat.getXVelocity( 1993 velocityTracker, mActivePointerId); 1994 mPopulatePending = true; 1995 final int width = getClientWidth(); 1996 final int scrollX = getScrollX(); 1997 final ItemInfo ii = infoForCurrentScrollPosition(); 1998 final int currentPage = ii.position; 1999 final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor; 2000 final int activePointerIndex = 2001 MotionEventCompat.findPointerIndex(ev, mActivePointerId); 2002 final float x = MotionEventCompat.getX(ev, activePointerIndex); 2003 final int totalDelta = (int) (x - mInitialMotionX); 2004 int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity, 2005 totalDelta); 2006 setCurrentItemInternal(nextPage, true, true, initialVelocity); 2007 2008 mActivePointerId = INVALID_POINTER; 2009 endDrag(); 2010 needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease(); 2011 } 2012 break; 2013 case MotionEvent.ACTION_CANCEL: 2014 if (mIsBeingDragged) { 2015 scrollToItem(mCurItem, true, 0, false); 2016 mActivePointerId = INVALID_POINTER; 2017 endDrag(); 2018 needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease(); 2019 } 2020 break; 2021 case MotionEventCompat.ACTION_POINTER_DOWN: { 2022 final int index = MotionEventCompat.getActionIndex(ev); 2023 final float x = MotionEventCompat.getX(ev, index); 2024 mLastMotionX = x; 2025 mActivePointerId = MotionEventCompat.getPointerId(ev, index); 2026 break; 2027 } 2028 case MotionEventCompat.ACTION_POINTER_UP: 2029 onSecondaryPointerUp(ev); 2030 mLastMotionX = MotionEventCompat.getX(ev, 2031 MotionEventCompat.findPointerIndex(ev, mActivePointerId)); 2032 break; 2033 } 2034 if (needsInvalidate) { 2035 ViewCompat.postInvalidateOnAnimation(this); 2036 } 2037 return true; 2038 } 2039 2040 private boolean performDrag(float x) { 2041 boolean needsInvalidate = false; 2042 2043 final float deltaX = mLastMotionX - x; 2044 mLastMotionX = x; 2045 2046 float oldScrollX = getScrollX(); 2047 float scrollX = oldScrollX + deltaX; 2048 final int width = getClientWidth(); 2049 2050 float leftBound = width * mFirstOffset; 2051 float rightBound = width * mLastOffset; 2052 boolean leftAbsolute = true; 2053 boolean rightAbsolute = true; 2054 2055 final ItemInfo firstItem = mItems.get(0); 2056 final ItemInfo lastItem = mItems.get(mItems.size() - 1); 2057 if (firstItem.position != 0) { 2058 leftAbsolute = false; 2059 leftBound = firstItem.offset * width; 2060 } 2061 if (lastItem.position != mAdapter.getCount() - 1) { 2062 rightAbsolute = false; 2063 rightBound = lastItem.offset * width; 2064 } 2065 2066 if (scrollX < leftBound) { 2067 if (leftAbsolute) { 2068 float over = leftBound - scrollX; 2069 needsInvalidate = mLeftEdge.onPull(Math.abs(over) / width); 2070 } 2071 scrollX = leftBound; 2072 } else if (scrollX > rightBound) { 2073 if (rightAbsolute) { 2074 float over = scrollX - rightBound; 2075 needsInvalidate = mRightEdge.onPull(Math.abs(over) / width); 2076 } 2077 scrollX = rightBound; 2078 } 2079 // Don't lose the rounded component 2080 mLastMotionX += scrollX - (int) scrollX; 2081 scrollTo((int) scrollX, getScrollY()); 2082 pageScrolled((int) scrollX); 2083 2084 return needsInvalidate; 2085 } 2086 2087 /** 2088 * @return Info about the page at the current scroll position. 2089 * This can be synthetic for a missing middle page; the 'object' field can be null. 2090 */ 2091 private ItemInfo infoForCurrentScrollPosition() { 2092 final int width = getClientWidth(); 2093 final float scrollOffset = width > 0 ? (float) getScrollX() / width : 0; 2094 final float marginOffset = width > 0 ? (float) mPageMargin / width : 0; 2095 int lastPos = -1; 2096 float lastOffset = 0.f; 2097 float lastWidth = 0.f; 2098 boolean first = true; 2099 2100 ItemInfo lastItem = null; 2101 for (int i = 0; i < mItems.size(); i++) { 2102 ItemInfo ii = mItems.get(i); 2103 float offset; 2104 if (!first && ii.position != lastPos + 1) { 2105 // Create a synthetic item for a missing page. 2106 ii = mTempItem; 2107 ii.offset = lastOffset + lastWidth + marginOffset; 2108 ii.position = lastPos + 1; 2109 ii.widthFactor = mAdapter.getPageWidth(ii.position); 2110 i--; 2111 } 2112 offset = ii.offset; 2113 2114 final float leftBound = offset; 2115 final float rightBound = offset + ii.widthFactor + marginOffset; 2116 if (first || scrollOffset >= leftBound) { 2117 if (scrollOffset < rightBound || i == mItems.size() - 1) { 2118 return ii; 2119 } 2120 } else { 2121 return lastItem; 2122 } 2123 first = false; 2124 lastPos = ii.position; 2125 lastOffset = offset; 2126 lastWidth = ii.widthFactor; 2127 lastItem = ii; 2128 } 2129 2130 return lastItem; 2131 } 2132 2133 private int determineTargetPage(int currentPage, float pageOffset, int velocity, int deltaX) { 2134 int targetPage; 2135 if (Math.abs(deltaX) > mFlingDistance && Math.abs(velocity) > mMinimumVelocity) { 2136 targetPage = velocity > 0 ? currentPage : currentPage + 1; 2137 } else { 2138 final float truncator = currentPage >= mCurItem ? 0.4f : 0.6f; 2139 targetPage = (int) (currentPage + pageOffset + truncator); 2140 } 2141 2142 if (mItems.size() > 0) { 2143 final ItemInfo firstItem = mItems.get(0); 2144 final ItemInfo lastItem = mItems.get(mItems.size() - 1); 2145 2146 // Only let the user target pages we have items for 2147 targetPage = Math.max(firstItem.position, Math.min(targetPage, lastItem.position)); 2148 } 2149 2150 return targetPage; 2151 } 2152 2153 @Override 2154 public void draw(Canvas canvas) { 2155 super.draw(canvas); 2156 boolean needsInvalidate = false; 2157 2158 final int overScrollMode = ViewCompat.getOverScrollMode(this); 2159 if (overScrollMode == ViewCompat.OVER_SCROLL_ALWAYS || 2160 (overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS && 2161 mAdapter != null && mAdapter.getCount() > 1)) { 2162 if (!mLeftEdge.isFinished()) { 2163 final int restoreCount = canvas.save(); 2164 final int height = getHeight() - getPaddingTop() - getPaddingBottom(); 2165 final int width = getWidth(); 2166 2167 canvas.rotate(270); 2168 canvas.translate(-height + getPaddingTop(), mFirstOffset * width); 2169 mLeftEdge.setSize(height, width); 2170 needsInvalidate |= mLeftEdge.draw(canvas); 2171 canvas.restoreToCount(restoreCount); 2172 } 2173 if (!mRightEdge.isFinished()) { 2174 final int restoreCount = canvas.save(); 2175 final int width = getWidth(); 2176 final int height = getHeight() - getPaddingTop() - getPaddingBottom(); 2177 2178 canvas.rotate(90); 2179 canvas.translate(-getPaddingTop(), -(mLastOffset + 1) * width); 2180 mRightEdge.setSize(height, width); 2181 needsInvalidate |= mRightEdge.draw(canvas); 2182 canvas.restoreToCount(restoreCount); 2183 } 2184 } else { 2185 mLeftEdge.finish(); 2186 mRightEdge.finish(); 2187 } 2188 2189 if (needsInvalidate) { 2190 // Keep animating 2191 ViewCompat.postInvalidateOnAnimation(this); 2192 } 2193 } 2194 2195 @Override 2196 protected void onDraw(Canvas canvas) { 2197 super.onDraw(canvas); 2198 2199 // Draw the margin drawable between pages if needed. 2200 if (mPageMargin > 0 && mMarginDrawable != null && mItems.size() > 0 && mAdapter != null) { 2201 final int scrollX = getScrollX(); 2202 final int width = getWidth(); 2203 2204 final float marginOffset = (float) mPageMargin / width; 2205 int itemIndex = 0; 2206 ItemInfo ii = mItems.get(0); 2207 float offset = ii.offset; 2208 final int itemCount = mItems.size(); 2209 final int firstPos = ii.position; 2210 final int lastPos = mItems.get(itemCount - 1).position; 2211 for (int pos = firstPos; pos < lastPos; pos++) { 2212 while (pos > ii.position && itemIndex < itemCount) { 2213 ii = mItems.get(++itemIndex); 2214 } 2215 2216 float drawAt; 2217 if (pos == ii.position) { 2218 drawAt = (ii.offset + ii.widthFactor) * width; 2219 offset = ii.offset + ii.widthFactor + marginOffset; 2220 } else { 2221 float widthFactor = mAdapter.getPageWidth(pos); 2222 drawAt = (offset + widthFactor) * width; 2223 offset += widthFactor + marginOffset; 2224 } 2225 2226 if (drawAt + mPageMargin > scrollX) { 2227 mMarginDrawable.setBounds((int) drawAt, mTopPageBounds, 2228 (int) (drawAt + mPageMargin + 0.5f), mBottomPageBounds); 2229 mMarginDrawable.draw(canvas); 2230 } 2231 2232 if (drawAt > scrollX + width) { 2233 break; // No more visible, no sense in continuing 2234 } 2235 } 2236 } 2237 } 2238 2239 /** 2240 * Start a fake drag of the pager. 2241 * 2242 * <p>A fake drag can be useful if you want to synchronize the motion of the ViewPager 2243 * with the touch scrolling of another view, while still letting the ViewPager 2244 * control the snapping motion and fling behavior. (e.g. parallax-scrolling tabs.) 2245 * Call {@link #fakeDragBy(float)} to simulate the actual drag motion. Call 2246 * {@link #endFakeDrag()} to complete the fake drag and fling as necessary. 2247 * 2248 * <p>During a fake drag the ViewPager will ignore all touch events. If a real drag 2249 * is already in progress, this method will return false. 2250 * 2251 * @return true if the fake drag began successfully, false if it could not be started. 2252 * 2253 * @see #fakeDragBy(float) 2254 * @see #endFakeDrag() 2255 */ 2256 public boolean beginFakeDrag() { 2257 if (mIsBeingDragged) { 2258 return false; 2259 } 2260 mFakeDragging = true; 2261 setScrollState(SCROLL_STATE_DRAGGING); 2262 mInitialMotionX = mLastMotionX = 0; 2263 if (mVelocityTracker == null) { 2264 mVelocityTracker = VelocityTracker.obtain(); 2265 } else { 2266 mVelocityTracker.clear(); 2267 } 2268 final long time = SystemClock.uptimeMillis(); 2269 final MotionEvent ev = MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, 0, 0, 0); 2270 mVelocityTracker.addMovement(ev); 2271 ev.recycle(); 2272 mFakeDragBeginTime = time; 2273 return true; 2274 } 2275 2276 /** 2277 * End a fake drag of the pager. 2278 * 2279 * @see #beginFakeDrag() 2280 * @see #fakeDragBy(float) 2281 */ 2282 public void endFakeDrag() { 2283 if (!mFakeDragging) { 2284 throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first."); 2285 } 2286 2287 final VelocityTracker velocityTracker = mVelocityTracker; 2288 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 2289 int initialVelocity = (int) VelocityTrackerCompat.getXVelocity( 2290 velocityTracker, mActivePointerId); 2291 mPopulatePending = true; 2292 final int width = getClientWidth(); 2293 final int scrollX = getScrollX(); 2294 final ItemInfo ii = infoForCurrentScrollPosition(); 2295 final int currentPage = ii.position; 2296 final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor; 2297 final int totalDelta = (int) (mLastMotionX - mInitialMotionX); 2298 int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity, 2299 totalDelta); 2300 setCurrentItemInternal(nextPage, true, true, initialVelocity); 2301 endDrag(); 2302 2303 mFakeDragging = false; 2304 } 2305 2306 /** 2307 * Fake drag by an offset in pixels. You must have called {@link #beginFakeDrag()} first. 2308 * 2309 * @param xOffset Offset in pixels to drag by. 2310 * @see #beginFakeDrag() 2311 * @see #endFakeDrag() 2312 */ 2313 public void fakeDragBy(float xOffset) { 2314 if (!mFakeDragging) { 2315 throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first."); 2316 } 2317 2318 mLastMotionX += xOffset; 2319 2320 float oldScrollX = getScrollX(); 2321 float scrollX = oldScrollX - xOffset; 2322 final int width = getClientWidth(); 2323 2324 float leftBound = width * mFirstOffset; 2325 float rightBound = width * mLastOffset; 2326 2327 final ItemInfo firstItem = mItems.get(0); 2328 final ItemInfo lastItem = mItems.get(mItems.size() - 1); 2329 if (firstItem.position != 0) { 2330 leftBound = firstItem.offset * width; 2331 } 2332 if (lastItem.position != mAdapter.getCount() - 1) { 2333 rightBound = lastItem.offset * width; 2334 } 2335 2336 if (scrollX < leftBound) { 2337 scrollX = leftBound; 2338 } else if (scrollX > rightBound) { 2339 scrollX = rightBound; 2340 } 2341 // Don't lose the rounded component 2342 mLastMotionX += scrollX - (int) scrollX; 2343 scrollTo((int) scrollX, getScrollY()); 2344 pageScrolled((int) scrollX); 2345 2346 // Synthesize an event for the VelocityTracker. 2347 final long time = SystemClock.uptimeMillis(); 2348 final MotionEvent ev = MotionEvent.obtain(mFakeDragBeginTime, time, MotionEvent.ACTION_MOVE, 2349 mLastMotionX, 0, 0); 2350 mVelocityTracker.addMovement(ev); 2351 ev.recycle(); 2352 } 2353 2354 /** 2355 * Returns true if a fake drag is in progress. 2356 * 2357 * @return true if currently in a fake drag, false otherwise. 2358 * 2359 * @see #beginFakeDrag() 2360 * @see #fakeDragBy(float) 2361 * @see #endFakeDrag() 2362 */ 2363 public boolean isFakeDragging() { 2364 return mFakeDragging; 2365 } 2366 2367 private void onSecondaryPointerUp(MotionEvent ev) { 2368 final int pointerIndex = MotionEventCompat.getActionIndex(ev); 2369 final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); 2370 if (pointerId == mActivePointerId) { 2371 // This was our active pointer going up. Choose a new 2372 // active pointer and adjust accordingly. 2373 final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 2374 mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex); 2375 mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); 2376 if (mVelocityTracker != null) { 2377 mVelocityTracker.clear(); 2378 } 2379 } 2380 } 2381 2382 private void endDrag() { 2383 mIsBeingDragged = false; 2384 mIsUnableToDrag = false; 2385 2386 if (mVelocityTracker != null) { 2387 mVelocityTracker.recycle(); 2388 mVelocityTracker = null; 2389 } 2390 } 2391 2392 private void setScrollingCacheEnabled(boolean enabled) { 2393 if (mScrollingCacheEnabled != enabled) { 2394 mScrollingCacheEnabled = enabled; 2395 if (USE_CACHE) { 2396 final int size = getChildCount(); 2397 for (int i = 0; i < size; ++i) { 2398 final View child = getChildAt(i); 2399 if (child.getVisibility() != GONE) { 2400 child.setDrawingCacheEnabled(enabled); 2401 } 2402 } 2403 } 2404 } 2405 } 2406 2407 /** 2408 * Tests scrollability within child views of v given a delta of dx. 2409 * 2410 * @param v View to test for horizontal scrollability 2411 * @param checkV Whether the view v passed should itself be checked for scrollability (true), 2412 * or just its children (false). 2413 * @param dx Delta scrolled in pixels 2414 * @param x X coordinate of the active touch point 2415 * @param y Y coordinate of the active touch point 2416 * @return true if child views of v can be scrolled by delta of dx. 2417 */ 2418 protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) { 2419 if (v instanceof ViewGroup) { 2420 final ViewGroup group = (ViewGroup) v; 2421 final int scrollX = v.getScrollX(); 2422 final int scrollY = v.getScrollY(); 2423 final int count = group.getChildCount(); 2424 // Count backwards - let topmost views consume scroll distance first. 2425 for (int i = count - 1; i >= 0; i--) { 2426 // TODO: Add versioned support here for transformed views. 2427 // This will not work for transformed views in Honeycomb+ 2428 final View child = group.getChildAt(i); 2429 if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() && 2430 y + scrollY >= child.getTop() && y + scrollY < child.getBottom() && 2431 canScroll(child, true, dx, x + scrollX - child.getLeft(), 2432 y + scrollY - child.getTop())) { 2433 return true; 2434 } 2435 } 2436 } 2437 2438 return checkV && ViewCompat.canScrollHorizontally(v, -dx); 2439 } 2440 2441 @Override 2442 public boolean dispatchKeyEvent(KeyEvent event) { 2443 // Let the focused view and/or our descendants get the key first 2444 return super.dispatchKeyEvent(event) || executeKeyEvent(event); 2445 } 2446 2447 /** 2448 * You can call this function yourself to have the scroll view perform 2449 * scrolling from a key event, just as if the event had been dispatched to 2450 * it by the view hierarchy. 2451 * 2452 * @param event The key event to execute. 2453 * @return Return true if the event was handled, else false. 2454 */ 2455 public boolean executeKeyEvent(KeyEvent event) { 2456 boolean handled = false; 2457 if (event.getAction() == KeyEvent.ACTION_DOWN) { 2458 switch (event.getKeyCode()) { 2459 case KeyEvent.KEYCODE_DPAD_LEFT: 2460 handled = arrowScroll(FOCUS_LEFT); 2461 break; 2462 case KeyEvent.KEYCODE_DPAD_RIGHT: 2463 handled = arrowScroll(FOCUS_RIGHT); 2464 break; 2465 case KeyEvent.KEYCODE_TAB: 2466 if (Build.VERSION.SDK_INT >= 11) { 2467 // The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD 2468 // before Android 3.0. Ignore the tab key on those devices. 2469 if (KeyEventCompat.hasNoModifiers(event)) { 2470 handled = arrowScroll(FOCUS_FORWARD); 2471 } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) { 2472 handled = arrowScroll(FOCUS_BACKWARD); 2473 } 2474 } 2475 break; 2476 } 2477 } 2478 return handled; 2479 } 2480 2481 public boolean arrowScroll(int direction) { 2482 View currentFocused = findFocus(); 2483 if (currentFocused == this) { 2484 currentFocused = null; 2485 } else if (currentFocused != null) { 2486 boolean isChild = false; 2487 for (ViewParent parent = currentFocused.getParent(); parent instanceof ViewGroup; 2488 parent = parent.getParent()) { 2489 if (parent == this) { 2490 isChild = true; 2491 break; 2492 } 2493 } 2494 if (!isChild) { 2495 // This would cause the focus search down below to fail in fun ways. 2496 final StringBuilder sb = new StringBuilder(); 2497 sb.append(currentFocused.getClass().getSimpleName()); 2498 for (ViewParent parent = currentFocused.getParent(); parent instanceof ViewGroup; 2499 parent = parent.getParent()) { 2500 sb.append(" => ").append(parent.getClass().getSimpleName()); 2501 } 2502 Log.e(TAG, "arrowScroll tried to find focus based on non-child " + 2503 "current focused view " + sb.toString()); 2504 currentFocused = null; 2505 } 2506 } 2507 2508 boolean handled = false; 2509 2510 View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, 2511 direction); 2512 if (nextFocused != null && nextFocused != currentFocused) { 2513 if (direction == View.FOCUS_LEFT) { 2514 // If there is nothing to the left, or this is causing us to 2515 // jump to the right, then what we really want to do is page left. 2516 final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left; 2517 final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left; 2518 if (currentFocused != null && nextLeft >= currLeft) { 2519 handled = pageLeft(); 2520 } else { 2521 handled = nextFocused.requestFocus(); 2522 } 2523 } else if (direction == View.FOCUS_RIGHT) { 2524 // If there is nothing to the right, or this is causing us to 2525 // jump to the left, then what we really want to do is page right. 2526 final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left; 2527 final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left; 2528 if (currentFocused != null && nextLeft <= currLeft) { 2529 handled = pageRight(); 2530 } else { 2531 handled = nextFocused.requestFocus(); 2532 } 2533 } 2534 } else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) { 2535 // Trying to move left and nothing there; try to page. 2536 handled = pageLeft(); 2537 } else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) { 2538 // Trying to move right and nothing there; try to page. 2539 handled = pageRight(); 2540 } 2541 if (handled) { 2542 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction)); 2543 } 2544 return handled; 2545 } 2546 2547 private Rect getChildRectInPagerCoordinates(Rect outRect, View child) { 2548 if (outRect == null) { 2549 outRect = new Rect(); 2550 } 2551 if (child == null) { 2552 outRect.set(0, 0, 0, 0); 2553 return outRect; 2554 } 2555 outRect.left = child.getLeft(); 2556 outRect.right = child.getRight(); 2557 outRect.top = child.getTop(); 2558 outRect.bottom = child.getBottom(); 2559 2560 ViewParent parent = child.getParent(); 2561 while (parent instanceof ViewGroup && parent != this) { 2562 final ViewGroup group = (ViewGroup) parent; 2563 outRect.left += group.getLeft(); 2564 outRect.right += group.getRight(); 2565 outRect.top += group.getTop(); 2566 outRect.bottom += group.getBottom(); 2567 2568 parent = group.getParent(); 2569 } 2570 return outRect; 2571 } 2572 2573 boolean pageLeft() { 2574 if (mCurItem > 0) { 2575 setCurrentItem(mCurItem-1, true); 2576 return true; 2577 } 2578 return false; 2579 } 2580 2581 boolean pageRight() { 2582 if (mAdapter != null && mCurItem < (mAdapter.getCount()-1)) { 2583 setCurrentItem(mCurItem+1, true); 2584 return true; 2585 } 2586 return false; 2587 } 2588 2589 /** 2590 * We only want the current page that is being shown to be focusable. 2591 */ 2592 @Override 2593 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 2594 final int focusableCount = views.size(); 2595 2596 final int descendantFocusability = getDescendantFocusability(); 2597 2598 if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) { 2599 for (int i = 0; i < getChildCount(); i++) { 2600 final View child = getChildAt(i); 2601 if (child.getVisibility() == VISIBLE) { 2602 ItemInfo ii = infoForChild(child); 2603 if (ii != null && ii.position == mCurItem) { 2604 child.addFocusables(views, direction, focusableMode); 2605 } 2606 } 2607 } 2608 } 2609 2610 // we add ourselves (if focusable) in all cases except for when we are 2611 // FOCUS_AFTER_DESCENDANTS and there are some descendants focusable. this is 2612 // to avoid the focus search finding layouts when a more precise search 2613 // among the focusable children would be more interesting. 2614 if ( 2615 descendantFocusability != FOCUS_AFTER_DESCENDANTS || 2616 // No focusable descendants 2617 (focusableCount == views.size())) { 2618 // Note that we can't call the superclass here, because it will 2619 // add all views in. So we need to do the same thing View does. 2620 if (!isFocusable()) { 2621 return; 2622 } 2623 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 2624 isInTouchMode() && !isFocusableInTouchMode()) { 2625 return; 2626 } 2627 if (views != null) { 2628 views.add(this); 2629 } 2630 } 2631 } 2632 2633 /** 2634 * We only want the current page that is being shown to be touchable. 2635 */ 2636 @Override 2637 public void addTouchables(ArrayList<View> views) { 2638 // Note that we don't call super.addTouchables(), which means that 2639 // we don't call View.addTouchables(). This is okay because a ViewPager 2640 // is itself not touchable. 2641 for (int i = 0; i < getChildCount(); i++) { 2642 final View child = getChildAt(i); 2643 if (child.getVisibility() == VISIBLE) { 2644 ItemInfo ii = infoForChild(child); 2645 if (ii != null && ii.position == mCurItem) { 2646 child.addTouchables(views); 2647 } 2648 } 2649 } 2650 } 2651 2652 /** 2653 * We only want the current page that is being shown to be focusable. 2654 */ 2655 @Override 2656 protected boolean onRequestFocusInDescendants(int direction, 2657 Rect previouslyFocusedRect) { 2658 int index; 2659 int increment; 2660 int end; 2661 int count = getChildCount(); 2662 if ((direction & FOCUS_FORWARD) != 0) { 2663 index = 0; 2664 increment = 1; 2665 end = count; 2666 } else { 2667 index = count - 1; 2668 increment = -1; 2669 end = -1; 2670 } 2671 for (int i = index; i != end; i += increment) { 2672 View child = getChildAt(i); 2673 if (child.getVisibility() == VISIBLE) { 2674 ItemInfo ii = infoForChild(child); 2675 if (ii != null && ii.position == mCurItem) { 2676 if (child.requestFocus(direction, previouslyFocusedRect)) { 2677 return true; 2678 } 2679 } 2680 } 2681 } 2682 return false; 2683 } 2684 2685 @Override 2686 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 2687 // ViewPagers should only report accessibility info for the current page, 2688 // otherwise things get very confusing. 2689 2690 // TODO: Should this note something about the paging container? 2691 2692 final int childCount = getChildCount(); 2693 for (int i = 0; i < childCount; i++) { 2694 final View child = getChildAt(i); 2695 if (child.getVisibility() == VISIBLE) { 2696 final ItemInfo ii = infoForChild(child); 2697 if (ii != null && ii.position == mCurItem && 2698 child.dispatchPopulateAccessibilityEvent(event)) { 2699 return true; 2700 } 2701 } 2702 } 2703 2704 return false; 2705 } 2706 2707 @Override 2708 protected ViewGroup.LayoutParams generateDefaultLayoutParams() { 2709 return new LayoutParams(); 2710 } 2711 2712 @Override 2713 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { 2714 return generateDefaultLayoutParams(); 2715 } 2716 2717 @Override 2718 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { 2719 return p instanceof LayoutParams && super.checkLayoutParams(p); 2720 } 2721 2722 @Override 2723 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { 2724 return new LayoutParams(getContext(), attrs); 2725 } 2726 2727 class MyAccessibilityDelegate extends AccessibilityDelegateCompat { 2728 2729 @Override 2730 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 2731 super.onInitializeAccessibilityEvent(host, event); 2732 event.setClassName(ViewPager.class.getName()); 2733 } 2734 2735 @Override 2736 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { 2737 super.onInitializeAccessibilityNodeInfo(host, info); 2738 info.setClassName(ViewPager.class.getName()); 2739 info.setScrollable(mAdapter != null && mAdapter.getCount() > 1); 2740 if (mAdapter != null && mCurItem >= 0 && mCurItem < mAdapter.getCount() - 1) { 2741 info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD); 2742 } 2743 if (mAdapter != null && mCurItem > 0 && mCurItem < mAdapter.getCount()) { 2744 info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD); 2745 } 2746 } 2747 2748 @Override 2749 public boolean performAccessibilityAction(View host, int action, Bundle args) { 2750 if (super.performAccessibilityAction(host, action, args)) { 2751 return true; 2752 } 2753 switch (action) { 2754 case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: { 2755 if (mAdapter != null && mCurItem >= 0 && mCurItem < mAdapter.getCount() - 1) { 2756 setCurrentItem(mCurItem + 1); 2757 return true; 2758 } 2759 } return false; 2760 case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: { 2761 if (mAdapter != null && mCurItem > 0 && mCurItem < mAdapter.getCount()) { 2762 setCurrentItem(mCurItem - 1); 2763 return true; 2764 } 2765 } return false; 2766 } 2767 return false; 2768 } 2769 } 2770 2771 private class PagerObserver extends DataSetObserver { 2772 @Override 2773 public void onChanged() { 2774 dataSetChanged(); 2775 } 2776 @Override 2777 public void onInvalidated() { 2778 dataSetChanged(); 2779 } 2780 } 2781 2782 /** 2783 * Layout parameters that should be supplied for views added to a 2784 * ViewPager. 2785 */ 2786 public static class LayoutParams extends ViewGroup.LayoutParams { 2787 /** 2788 * true if this view is a decoration on the pager itself and not 2789 * a view supplied by the adapter. 2790 */ 2791 public boolean isDecor; 2792 2793 /** 2794 * Gravity setting for use on decor views only: 2795 * Where to position the view page within the overall ViewPager 2796 * container; constants are defined in {@link android.view.Gravity}. 2797 */ 2798 public int gravity; 2799 2800 /** 2801 * Width as a 0-1 multiplier of the measured pager width 2802 */ 2803 float widthFactor = 0.f; 2804 2805 /** 2806 * true if this view was added during layout and needs to be measured 2807 * before being positioned. 2808 */ 2809 boolean needsMeasure; 2810 2811 /** 2812 * Adapter position this view is for if !isDecor 2813 */ 2814 int position; 2815 2816 /** 2817 * Current child index within the ViewPager that this view occupies 2818 */ 2819 int childIndex; 2820 2821 public LayoutParams() { 2822 super(FILL_PARENT, FILL_PARENT); 2823 } 2824 2825 public LayoutParams(Context context, AttributeSet attrs) { 2826 super(context, attrs); 2827 2828 final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS); 2829 gravity = a.getInteger(0, Gravity.TOP); 2830 a.recycle(); 2831 } 2832 } 2833 2834 static class ViewPositionComparator implements Comparator<View> { 2835 @Override 2836 public int compare(View lhs, View rhs) { 2837 final LayoutParams llp = (LayoutParams) lhs.getLayoutParams(); 2838 final LayoutParams rlp = (LayoutParams) rhs.getLayoutParams(); 2839 if (llp.isDecor != rlp.isDecor) { 2840 return llp.isDecor ? 1 : -1; 2841 } 2842 return llp.position - rlp.position; 2843 } 2844 } 2845} 2846