ViewPager.java revision 1ccb8bcb79557d861de7f271c13e2fd8e54e012a
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.TypedArray; 21import android.database.DataSetObserver; 22import android.graphics.Canvas; 23import android.graphics.Rect; 24import android.graphics.drawable.Drawable; 25import android.os.Parcel; 26import android.os.Parcelable; 27import android.os.SystemClock; 28import android.support.v4.os.ParcelableCompat; 29import android.support.v4.os.ParcelableCompatCreatorCallbacks; 30import android.support.v4.widget.EdgeEffectCompat; 31import android.util.AttributeSet; 32import android.util.Log; 33import android.view.FocusFinder; 34import android.view.Gravity; 35import android.view.KeyEvent; 36import android.view.MotionEvent; 37import android.view.SoundEffectConstants; 38import android.view.VelocityTracker; 39import android.view.View; 40import android.view.ViewConfiguration; 41import android.view.ViewGroup; 42import android.view.ViewParent; 43import android.view.accessibility.AccessibilityEvent; 44import android.view.animation.Interpolator; 45import android.widget.Scroller; 46 47import java.util.ArrayList; 48import java.util.Collections; 49import java.util.Comparator; 50 51/** 52 * Layout manager that allows the user to flip left and right 53 * through pages of data. You supply an implementation of a 54 * {@link PagerAdapter} to generate the pages that the view shows. 55 * 56 * <p>Note this class is currently under early design and 57 * development. The API will likely change in later updates of 58 * the compatibility library, requiring changes to the source code 59 * of apps when they are compiled against the newer version.</p> 60 */ 61public class ViewPager extends ViewGroup { 62 private static final String TAG = "ViewPager"; 63 private static final boolean DEBUG = false; 64 65 private static final boolean USE_CACHE = false; 66 67 private static final int DEFAULT_OFFSCREEN_PAGES = 1; 68 private static final int MAX_SETTLE_DURATION = 600; // ms 69 70 private static final int[] LAYOUT_ATTRS = new int[] { 71 android.R.attr.layout_gravity 72 }; 73 74 static class ItemInfo { 75 Object object; 76 int position; 77 boolean scrolling; 78 } 79 80 private static final Comparator<ItemInfo> COMPARATOR = new Comparator<ItemInfo>(){ 81 @Override 82 public int compare(ItemInfo lhs, ItemInfo rhs) { 83 return lhs.position - rhs.position; 84 }}; 85 86 private static final Interpolator sInterpolator = new Interpolator() { 87 public float getInterpolation(float t) { 88 // _o(t) = t * t * ((tension + 1) * t + tension) 89 // o(t) = _o(t - 1) + 1 90 t -= 1.0f; 91 return t * t * t + 1.0f; 92 } 93 }; 94 95 private final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>(); 96 97 private PagerAdapter mAdapter; 98 private int mCurItem; // Index of currently displayed page. 99 private int mRestoredCurItem = -1; 100 private Parcelable mRestoredAdapterState = null; 101 private ClassLoader mRestoredClassLoader = null; 102 private Scroller mScroller; 103 private PagerObserver mObserver; 104 105 private int mPageMargin; 106 private Drawable mMarginDrawable; 107 private int mTopPageBounds; 108 private int mBottomPageBounds; 109 110 private int mChildWidthMeasureSpec; 111 private int mChildHeightMeasureSpec; 112 private boolean mInLayout; 113 114 private boolean mScrollingCacheEnabled; 115 116 private boolean mPopulatePending; 117 private boolean mIsPopulating; 118 private boolean mScrolling; 119 private int mOffscreenPageLimit = DEFAULT_OFFSCREEN_PAGES; 120 121 private boolean mIsBeingDragged; 122 private boolean mIsUnableToDrag; 123 private int mTouchSlop; 124 private float mInitialMotionX; 125 /** 126 * Position of the last motion event. 127 */ 128 private float mLastMotionX; 129 private float mLastMotionY; 130 /** 131 * ID of the active pointer. This is used to retain consistency during 132 * drags/flings if multiple pointers are used. 133 */ 134 private int mActivePointerId = INVALID_POINTER; 135 /** 136 * Sentinel value for no current active pointer. 137 * Used by {@link #mActivePointerId}. 138 */ 139 private static final int INVALID_POINTER = -1; 140 141 /** 142 * Determines speed during touch scrolling 143 */ 144 private VelocityTracker mVelocityTracker; 145 private int mMinimumVelocity; 146 private int mMaximumVelocity; 147 private float mBaseLineFlingVelocity; 148 private float mFlingVelocityInfluence; 149 150 private boolean mFakeDragging; 151 private long mFakeDragBeginTime; 152 153 private EdgeEffectCompat mLeftEdge; 154 private EdgeEffectCompat mRightEdge; 155 156 private boolean mFirstLayout = true; 157 private boolean mCalledSuper; 158 private int mDecorChildCount; 159 160 private OnPageChangeListener mOnPageChangeListener; 161 private OnPageChangeListener mInternalPageChangeListener; 162 private OnAdapterChangeListener mAdapterChangeListener; 163 164 /** 165 * Indicates that the pager is in an idle, settled state. The current page 166 * is fully in view and no animation is in progress. 167 */ 168 public static final int SCROLL_STATE_IDLE = 0; 169 170 /** 171 * Indicates that the pager is currently being dragged by the user. 172 */ 173 public static final int SCROLL_STATE_DRAGGING = 1; 174 175 /** 176 * Indicates that the pager is in the process of settling to a final position. 177 */ 178 public static final int SCROLL_STATE_SETTLING = 2; 179 180 private int mScrollState = SCROLL_STATE_IDLE; 181 182 /** 183 * Callback interface for responding to changing state of the selected page. 184 */ 185 public interface OnPageChangeListener { 186 187 /** 188 * This method will be invoked when the current page is scrolled, either as part 189 * of a programmatically initiated smooth scroll or a user initiated touch scroll. 190 * 191 * @param position Position index of the first page currently being displayed. 192 * Page position+1 will be visible if positionOffset is nonzero. 193 * @param positionOffset Value from [0, 1) indicating the offset from the page at position. 194 * @param positionOffsetPixels Value in pixels indicating the offset from position. 195 */ 196 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels); 197 198 /** 199 * This method will be invoked when a new page becomes selected. Animation is not 200 * necessarily complete. 201 * 202 * @param position Position index of the new selected page. 203 */ 204 public void onPageSelected(int position); 205 206 /** 207 * Called when the scroll state changes. Useful for discovering when the user 208 * begins dragging, when the pager is automatically settling to the current page, 209 * or when it is fully stopped/idle. 210 * 211 * @param state The new scroll state. 212 * @see ViewPager#SCROLL_STATE_IDLE 213 * @see ViewPager#SCROLL_STATE_DRAGGING 214 * @see ViewPager#SCROLL_STATE_SETTLING 215 */ 216 public void onPageScrollStateChanged(int state); 217 } 218 219 /** 220 * Simple implementation of the {@link OnPageChangeListener} interface with stub 221 * implementations of each method. Extend this if you do not intend to override 222 * every method of {@link OnPageChangeListener}. 223 */ 224 public static class SimpleOnPageChangeListener implements OnPageChangeListener { 225 @Override 226 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 227 // This space for rent 228 } 229 230 @Override 231 public void onPageSelected(int position) { 232 // This space for rent 233 } 234 235 @Override 236 public void onPageScrollStateChanged(int state) { 237 // This space for rent 238 } 239 } 240 241 /** 242 * Used internally to monitor when adapters are switched. 243 */ 244 interface OnAdapterChangeListener { 245 public void onAdapterChanged(PagerAdapter oldAdapter, PagerAdapter newAdapter); 246 } 247 248 /** 249 * Used internally to tag special types of child views that should be added as 250 * pager decorations by default. 251 */ 252 interface Decor {} 253 254 public ViewPager(Context context) { 255 super(context); 256 initViewPager(); 257 } 258 259 public ViewPager(Context context, AttributeSet attrs) { 260 super(context, attrs); 261 initViewPager(); 262 } 263 264 void initViewPager() { 265 setWillNotDraw(false); 266 setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); 267 setFocusable(true); 268 final Context context = getContext(); 269 mScroller = new Scroller(context, sInterpolator); 270 final ViewConfiguration configuration = ViewConfiguration.get(context); 271 mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); 272 mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); 273 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); 274 mLeftEdge = new EdgeEffectCompat(context); 275 mRightEdge = new EdgeEffectCompat(context); 276 277 float density = context.getResources().getDisplayMetrics().density; 278 mBaseLineFlingVelocity = 2500.0f * density; 279 mFlingVelocityInfluence = 0.4f; 280 } 281 282 private void setScrollState(int newState) { 283 if (mScrollState == newState) { 284 return; 285 } 286 287 mScrollState = newState; 288 if (mOnPageChangeListener != null) { 289 mOnPageChangeListener.onPageScrollStateChanged(newState); 290 } 291 } 292 293 /** 294 * Set a PagerAdapter that will supply views for this pager as needed. 295 * 296 * @param adapter Adapter to use 297 */ 298 public void setAdapter(PagerAdapter adapter) { 299 if (mAdapter != null) { 300 mAdapter.unregisterDataSetObserver(mObserver); 301 mAdapter.startUpdate(this); 302 for (int i = 0; i < mItems.size(); i++) { 303 final ItemInfo ii = mItems.get(i); 304 mAdapter.destroyItem(this, ii.position, ii.object); 305 } 306 mAdapter.finishUpdate(this); 307 mItems.clear(); 308 removeAllViews(); 309 mCurItem = 0; 310 scrollTo(0, 0); 311 } 312 313 final PagerAdapter oldAdapter = mAdapter; 314 mAdapter = adapter; 315 316 if (mAdapter != null) { 317 if (mObserver == null) { 318 mObserver = new PagerObserver(); 319 } 320 mAdapter.registerDataSetObserver(mObserver); 321 mPopulatePending = false; 322 if (mRestoredCurItem >= 0) { 323 mAdapter.restoreState(mRestoredAdapterState, mRestoredClassLoader); 324 setCurrentItemInternal(mRestoredCurItem, false, true); 325 mRestoredCurItem = -1; 326 mRestoredAdapterState = null; 327 mRestoredClassLoader = null; 328 } else { 329 populate(); 330 } 331 } 332 333 if (mAdapterChangeListener != null && oldAdapter != adapter) { 334 mAdapterChangeListener.onAdapterChanged(oldAdapter, adapter); 335 } 336 } 337 338 /** 339 * Retrieve the current adapter supplying pages. 340 * 341 * @return The currently registered PagerAdapter 342 */ 343 public PagerAdapter getAdapter() { 344 return mAdapter; 345 } 346 347 void setOnAdapterChangeListener(OnAdapterChangeListener listener) { 348 mAdapterChangeListener = listener; 349 } 350 351 /** 352 * Set the currently selected page. If the ViewPager has already been through its first 353 * layout there will be a smooth animated transition between the current item and the 354 * specified item. 355 * 356 * @param item Item index to select 357 */ 358 public void setCurrentItem(int item) { 359 mPopulatePending = false; 360 setCurrentItemInternal(item, !mFirstLayout, false); 361 } 362 363 /** 364 * Set the currently selected page. 365 * 366 * @param item Item index to select 367 * @param smoothScroll True to smoothly scroll to the new item, false to transition immediately 368 */ 369 public void setCurrentItem(int item, boolean smoothScroll) { 370 mPopulatePending = false; 371 setCurrentItemInternal(item, smoothScroll, false); 372 } 373 374 public int getCurrentItem() { 375 return mCurItem; 376 } 377 378 void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) { 379 setCurrentItemInternal(item, smoothScroll, always, 0); 380 } 381 382 void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) { 383 if (mAdapter == null || mAdapter.getCount() <= 0) { 384 setScrollingCacheEnabled(false); 385 return; 386 } 387 if (!always && mCurItem == item && mItems.size() != 0) { 388 setScrollingCacheEnabled(false); 389 return; 390 } 391 if (item < 0) { 392 item = 0; 393 } else if (item >= mAdapter.getCount()) { 394 item = mAdapter.getCount() - 1; 395 } 396 final int pageLimit = mOffscreenPageLimit; 397 if (item > (mCurItem + pageLimit) || item < (mCurItem - pageLimit)) { 398 // We are doing a jump by more than one page. To avoid 399 // glitches, we want to keep all current pages in the view 400 // until the scroll ends. 401 for (int i=0; i<mItems.size(); i++) { 402 mItems.get(i).scrolling = true; 403 } 404 } 405 final boolean dispatchSelected = mCurItem != item; 406 mCurItem = item; 407 populate(); 408 final int destX = (getWidth() + mPageMargin) * item; 409 if (smoothScroll) { 410 smoothScrollTo(destX, 0, velocity); 411 if (dispatchSelected && mOnPageChangeListener != null) { 412 mOnPageChangeListener.onPageSelected(item); 413 } 414 if (dispatchSelected && mInternalPageChangeListener != null) { 415 mInternalPageChangeListener.onPageSelected(item); 416 } 417 } else { 418 if (dispatchSelected && mOnPageChangeListener != null) { 419 mOnPageChangeListener.onPageSelected(item); 420 } 421 if (dispatchSelected && mInternalPageChangeListener != null) { 422 mInternalPageChangeListener.onPageSelected(item); 423 } 424 completeScroll(); 425 scrollTo(destX, 0); 426 } 427 } 428 429 /** 430 * Set a listener that will be invoked whenever the page changes or is incrementally 431 * scrolled. See {@link OnPageChangeListener}. 432 * 433 * @param listener Listener to set 434 */ 435 public void setOnPageChangeListener(OnPageChangeListener listener) { 436 mOnPageChangeListener = listener; 437 } 438 439 /** 440 * Set a separate OnPageChangeListener for internal use by the support library. 441 * 442 * @param listener Listener to set 443 * @return The old listener that was set, if any. 444 */ 445 OnPageChangeListener setInternalPageChangeListener(OnPageChangeListener listener) { 446 OnPageChangeListener oldListener = mInternalPageChangeListener; 447 mInternalPageChangeListener = listener; 448 return oldListener; 449 } 450 451 /** 452 * Returns the number of pages that will be retained to either side of the 453 * current page in the view hierarchy in an idle state. Defaults to 1. 454 * 455 * @return How many pages will be kept offscreen on either side 456 * @see #setOffscreenPageLimit(int) 457 */ 458 public int getOffscreenPageLimit() { 459 return mOffscreenPageLimit; 460 } 461 462 /** 463 * Set the number of pages that should be retained to either side of the 464 * current page in the view hierarchy in an idle state. Pages beyond this 465 * limit will be recreated from the adapter when needed. 466 * 467 * <p>This is offered as an optimization. If you know in advance the number 468 * of pages you will need to support or have lazy-loading mechanisms in place 469 * on your pages, tweaking this setting can have benefits in perceived smoothness 470 * of paging animations and interaction. If you have a small number of pages (3-4) 471 * that you can keep active all at once, less time will be spent in layout for 472 * newly created view subtrees as the user pages back and forth.</p> 473 * 474 * <p>You should keep this limit low, especially if your pages have complex layouts. 475 * This setting defaults to 1.</p> 476 * 477 * @param limit How many pages will be kept offscreen in an idle state. 478 */ 479 public void setOffscreenPageLimit(int limit) { 480 if (limit < DEFAULT_OFFSCREEN_PAGES) { 481 Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " + 482 DEFAULT_OFFSCREEN_PAGES); 483 limit = DEFAULT_OFFSCREEN_PAGES; 484 } 485 if (limit != mOffscreenPageLimit) { 486 mOffscreenPageLimit = limit; 487 populate(); 488 } 489 } 490 491 /** 492 * Set the margin between pages. 493 * 494 * @param marginPixels Distance between adjacent pages in pixels 495 * @see #getPageMargin() 496 * @see #setPageMarginDrawable(Drawable) 497 * @see #setPageMarginDrawable(int) 498 */ 499 public void setPageMargin(int marginPixels) { 500 final int oldMargin = mPageMargin; 501 mPageMargin = marginPixels; 502 503 final int width = getWidth(); 504 recomputeScrollPosition(width, width, marginPixels, oldMargin); 505 506 requestLayout(); 507 } 508 509 /** 510 * Return the margin between pages. 511 * 512 * @return The size of the margin in pixels 513 */ 514 public int getPageMargin() { 515 return mPageMargin; 516 } 517 518 /** 519 * Set a drawable that will be used to fill the margin between pages. 520 * 521 * @param d Drawable to display between pages 522 */ 523 public void setPageMarginDrawable(Drawable d) { 524 mMarginDrawable = d; 525 if (d != null) refreshDrawableState(); 526 setWillNotDraw(d == null); 527 invalidate(); 528 } 529 530 /** 531 * Set a drawable that will be used to fill the margin between pages. 532 * 533 * @param resId Resource ID of a drawable to display between pages 534 */ 535 public void setPageMarginDrawable(int resId) { 536 setPageMarginDrawable(getContext().getResources().getDrawable(resId)); 537 } 538 539 @Override 540 protected boolean verifyDrawable(Drawable who) { 541 return super.verifyDrawable(who) || who == mMarginDrawable; 542 } 543 544 @Override 545 protected void drawableStateChanged() { 546 super.drawableStateChanged(); 547 final Drawable d = mMarginDrawable; 548 if (d != null && d.isStateful()) { 549 d.setState(getDrawableState()); 550 } 551 } 552 553 // We want the duration of the page snap animation to be influenced by the distance that 554 // the screen has to travel, however, we don't want this duration to be effected in a 555 // purely linear fashion. Instead, we use this method to moderate the effect that the distance 556 // of travel has on the overall snap duration. 557 float distanceInfluenceForSnapDuration(float f) { 558 f -= 0.5f; // center the values about 0. 559 f *= 0.3f * Math.PI / 2.0f; 560 return (float) Math.sin(f); 561 } 562 563 /** 564 * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. 565 * 566 * @param x the number of pixels to scroll by on the X axis 567 * @param y the number of pixels to scroll by on the Y axis 568 */ 569 void smoothScrollTo(int x, int y) { 570 smoothScrollTo(x, y, 0); 571 } 572 573 /** 574 * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. 575 * 576 * @param x the number of pixels to scroll by on the X axis 577 * @param y the number of pixels to scroll by on the Y axis 578 * @param velocity the velocity associated with a fling, if applicable. (0 otherwise) 579 */ 580 void smoothScrollTo(int x, int y, int velocity) { 581 if (getChildCount() == 0) { 582 // Nothing to do. 583 setScrollingCacheEnabled(false); 584 return; 585 } 586 int sx = getScrollX(); 587 int sy = getScrollY(); 588 int dx = x - sx; 589 int dy = y - sy; 590 if (dx == 0 && dy == 0) { 591 completeScroll(); 592 setScrollState(SCROLL_STATE_IDLE); 593 return; 594 } 595 596 setScrollingCacheEnabled(true); 597 mScrolling = true; 598 setScrollState(SCROLL_STATE_SETTLING); 599 600 final float pageDelta = (float) Math.abs(dx) / (getWidth() + mPageMargin); 601 int duration = (int) (pageDelta * 100); 602 603 velocity = Math.abs(velocity); 604 if (velocity > 0) { 605 duration += (duration / (velocity / mBaseLineFlingVelocity)) * mFlingVelocityInfluence; 606 } else { 607 duration += 100; 608 } 609 duration = Math.min(duration, MAX_SETTLE_DURATION); 610 611 mScroller.startScroll(sx, sy, dx, dy, duration); 612 invalidate(); 613 } 614 615 void addNewItem(int position, int index) { 616 ItemInfo ii = new ItemInfo(); 617 ii.position = position; 618 ii.object = mAdapter.instantiateItem(this, position); 619 if (index < 0) { 620 mItems.add(ii); 621 } else { 622 mItems.add(index, ii); 623 } 624 } 625 626 void dataSetChanged() { 627 // This method only gets called if our observer is attached, so mAdapter is non-null. 628 629 boolean needPopulate = mItems.size() < 3 && mItems.size() < mAdapter.getCount(); 630 int newCurrItem = -1; 631 632 boolean isUpdating = false; 633 for (int i = 0; i < mItems.size(); i++) { 634 final ItemInfo ii = mItems.get(i); 635 final int newPos = mAdapter.getItemPosition(ii.object); 636 637 if (newPos == PagerAdapter.POSITION_UNCHANGED) { 638 continue; 639 } 640 641 if (newPos == PagerAdapter.POSITION_NONE) { 642 mItems.remove(i); 643 i--; 644 645 if (!isUpdating) { 646 mAdapter.startUpdate(this); 647 isUpdating = true; 648 } 649 650 mAdapter.destroyItem(this, ii.position, ii.object); 651 needPopulate = true; 652 653 if (mCurItem == ii.position) { 654 // Keep the current item in the valid range 655 newCurrItem = Math.max(0, Math.min(mCurItem, mAdapter.getCount() - 1)); 656 } 657 continue; 658 } 659 660 if (ii.position != newPos) { 661 if (ii.position == mCurItem) { 662 // Our current item changed position. Follow it. 663 newCurrItem = newPos; 664 } 665 666 ii.position = newPos; 667 needPopulate = true; 668 } 669 } 670 671 if (isUpdating) { 672 mAdapter.finishUpdate(this); 673 } 674 675 Collections.sort(mItems, COMPARATOR); 676 677 if (newCurrItem >= 0) { 678 // TODO This currently causes a jump. 679 setCurrentItemInternal(newCurrItem, false, true); 680 needPopulate = true; 681 } 682 if (needPopulate) { 683 populate(); 684 requestLayout(); 685 } 686 } 687 688 void populate() { 689 if (mAdapter == null) { 690 return; 691 } 692 693 // Bail now if we are waiting to populate. This is to hold off 694 // on creating views from the time the user releases their finger to 695 // fling to a new position until we have finished the scroll to 696 // that position, avoiding glitches from happening at that point. 697 if (mPopulatePending) { 698 if (DEBUG) Log.i(TAG, "populate is pending, skipping for now..."); 699 return; 700 } 701 702 // Also, don't populate until we are attached to a window. This is to 703 // avoid trying to populate before we have restored our view hierarchy 704 // state and conflicting with what is restored. 705 if (getWindowToken() == null) { 706 return; 707 } 708 709 mIsPopulating = true; 710 mAdapter.startUpdate(this); 711 712 final int pageLimit = mOffscreenPageLimit; 713 final int startPos = Math.max(0, mCurItem - pageLimit); 714 final int N = mAdapter.getCount(); 715 final int endPos = Math.min(N-1, mCurItem + pageLimit); 716 717 if (DEBUG) Log.v(TAG, "populating: startPos=" + startPos + " endPos=" + endPos); 718 719 // Add and remove pages in the existing list. 720 int lastPos = -1; 721 for (int i=0; i<mItems.size(); i++) { 722 ItemInfo ii = mItems.get(i); 723 if ((ii.position < startPos || ii.position > endPos) && !ii.scrolling) { 724 if (DEBUG) Log.i(TAG, "removing: " + ii.position + " @ " + i); 725 mItems.remove(i); 726 i--; 727 mAdapter.destroyItem(this, ii.position, ii.object); 728 } else if (lastPos < endPos && ii.position > startPos) { 729 // The next item is outside of our range, but we have a gap 730 // between it and the last item where we want to have a page 731 // shown. Fill in the gap. 732 lastPos++; 733 if (lastPos < startPos) { 734 lastPos = startPos; 735 } 736 while (lastPos <= endPos && lastPos < ii.position) { 737 if (DEBUG) Log.i(TAG, "inserting: " + lastPos + " @ " + i); 738 addNewItem(lastPos, i); 739 lastPos++; 740 i++; 741 } 742 } 743 lastPos = ii.position; 744 } 745 746 // Add any new pages we need at the end. 747 lastPos = mItems.size() > 0 ? mItems.get(mItems.size()-1).position : -1; 748 if (lastPos < endPos) { 749 lastPos++; 750 lastPos = lastPos > startPos ? lastPos : startPos; 751 while (lastPos <= endPos) { 752 if (DEBUG) Log.i(TAG, "appending: " + lastPos); 753 addNewItem(lastPos, -1); 754 lastPos++; 755 } 756 } 757 758 if (DEBUG) { 759 Log.i(TAG, "Current page list:"); 760 for (int i=0; i<mItems.size(); i++) { 761 Log.i(TAG, "#" + i + ": page " + mItems.get(i).position); 762 } 763 } 764 765 ItemInfo curItem = null; 766 for (int i=0; i<mItems.size(); i++) { 767 if (mItems.get(i).position == mCurItem) { 768 curItem = mItems.get(i); 769 break; 770 } 771 } 772 mAdapter.setPrimaryItem(this, mCurItem, curItem != null ? curItem.object : null); 773 774 mAdapter.finishUpdate(this); 775 mIsPopulating = false; 776 777 if (hasFocus()) { 778 View currentFocused = findFocus(); 779 ItemInfo ii = currentFocused != null ? infoForAnyChild(currentFocused) : null; 780 if (ii == null || ii.position != mCurItem) { 781 for (int i=0; i<getChildCount(); i++) { 782 View child = getChildAt(i); 783 ii = infoForChild(child); 784 if (ii != null && ii.position == mCurItem) { 785 if (child.requestFocus(FOCUS_FORWARD)) { 786 break; 787 } 788 } 789 } 790 } 791 } 792 } 793 794 public static class SavedState extends BaseSavedState { 795 int position; 796 Parcelable adapterState; 797 ClassLoader loader; 798 799 public SavedState(Parcelable superState) { 800 super(superState); 801 } 802 803 @Override 804 public void writeToParcel(Parcel out, int flags) { 805 super.writeToParcel(out, flags); 806 out.writeInt(position); 807 out.writeParcelable(adapterState, flags); 808 } 809 810 @Override 811 public String toString() { 812 return "FragmentPager.SavedState{" 813 + Integer.toHexString(System.identityHashCode(this)) 814 + " position=" + position + "}"; 815 } 816 817 public static final Parcelable.Creator<SavedState> CREATOR 818 = ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks<SavedState>() { 819 @Override 820 public SavedState createFromParcel(Parcel in, ClassLoader loader) { 821 return new SavedState(in, loader); 822 } 823 @Override 824 public SavedState[] newArray(int size) { 825 return new SavedState[size]; 826 } 827 }); 828 829 SavedState(Parcel in, ClassLoader loader) { 830 super(in); 831 if (loader == null) { 832 loader = getClass().getClassLoader(); 833 } 834 position = in.readInt(); 835 adapterState = in.readParcelable(loader); 836 this.loader = loader; 837 } 838 } 839 840 @Override 841 public Parcelable onSaveInstanceState() { 842 Parcelable superState = super.onSaveInstanceState(); 843 SavedState ss = new SavedState(superState); 844 ss.position = mCurItem; 845 if (mAdapter != null) { 846 ss.adapterState = mAdapter.saveState(); 847 } 848 return ss; 849 } 850 851 @Override 852 public void onRestoreInstanceState(Parcelable state) { 853 if (!(state instanceof SavedState)) { 854 super.onRestoreInstanceState(state); 855 return; 856 } 857 858 SavedState ss = (SavedState)state; 859 super.onRestoreInstanceState(ss.getSuperState()); 860 861 if (mAdapter != null) { 862 mAdapter.restoreState(ss.adapterState, ss.loader); 863 setCurrentItemInternal(ss.position, false, true); 864 } else { 865 mRestoredCurItem = ss.position; 866 mRestoredAdapterState = ss.adapterState; 867 mRestoredClassLoader = ss.loader; 868 } 869 } 870 871 @Override 872 public void addView(View child, int index, ViewGroup.LayoutParams params) { 873 if (!checkLayoutParams(params)) { 874 params = generateLayoutParams(params); 875 } 876 final LayoutParams lp = (LayoutParams) params; 877 lp.isDecor |= child instanceof Decor; 878 if (mInLayout) { 879 if (lp != null && lp.isDecor) { 880 throw new IllegalStateException("Cannot add pager decor view during layout"); 881 } 882 addViewInLayout(child, index, params); 883 child.measure(mChildWidthMeasureSpec, mChildHeightMeasureSpec); 884 } else { 885 super.addView(child, index, params); 886 } 887 888 if (USE_CACHE) { 889 if (child.getVisibility() != GONE) { 890 child.setDrawingCacheEnabled(mScrollingCacheEnabled); 891 } else { 892 child.setDrawingCacheEnabled(false); 893 } 894 } 895 } 896 897 ItemInfo infoForChild(View child) { 898 for (int i=0; i<mItems.size(); i++) { 899 ItemInfo ii = mItems.get(i); 900 if (mAdapter.isViewFromObject(child, ii.object)) { 901 return ii; 902 } 903 } 904 return null; 905 } 906 907 ItemInfo infoForAnyChild(View child) { 908 ViewParent parent; 909 while ((parent=child.getParent()) != this) { 910 if (parent == null || !(parent instanceof View)) { 911 return null; 912 } 913 child = (View)parent; 914 } 915 return infoForChild(child); 916 } 917 918 @Override 919 protected void onAttachedToWindow() { 920 super.onAttachedToWindow(); 921 mFirstLayout = true; 922 } 923 924 @Override 925 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 926 // For simple implementation, or internal size is always 0. 927 // We depend on the container to specify the layout size of 928 // our view. We can't really know what it is since we will be 929 // adding and removing different arbitrary views and do not 930 // want the layout to change as this happens. 931 setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), 932 getDefaultSize(0, heightMeasureSpec)); 933 934 // Children are just made to fill our space. 935 int childWidthSize = getMeasuredWidth() - getPaddingLeft() - getPaddingRight(); 936 int childHeightSize = getMeasuredHeight() - getPaddingTop() - getPaddingBottom(); 937 938 /* 939 * Make sure all children have been properly measured. Decor views first. 940 * Right now we cheat and make this less complicated by assuming decor 941 * views won't intersect. We will pin to edges based on gravity. 942 */ 943 final int size = getChildCount(); 944 for (int i = 0; i < size; ++i) { 945 final View child = getChildAt(i); 946 if (child.getVisibility() != GONE) { 947 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 948 if (lp != null && lp.isDecor) { 949 final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK; 950 final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK; 951 Log.d(TAG, "gravity: " + lp.gravity + " hgrav: " + hgrav + " vgrav: " + vgrav); 952 int widthMode = MeasureSpec.AT_MOST; 953 int heightMode = MeasureSpec.AT_MOST; 954 boolean consumeVertical = vgrav == Gravity.TOP || vgrav == Gravity.BOTTOM; 955 boolean consumeHorizontal = hgrav == Gravity.LEFT || hgrav == Gravity.RIGHT; 956 957 if (consumeVertical) { 958 widthMode = MeasureSpec.EXACTLY; 959 } else if (consumeHorizontal) { 960 heightMode = MeasureSpec.EXACTLY; 961 } 962 963 final int widthSpec = MeasureSpec.makeMeasureSpec(childWidthSize, widthMode); 964 final int heightSpec = MeasureSpec.makeMeasureSpec(childHeightSize, heightMode); 965 child.measure(widthSpec, heightSpec); 966 967 if (consumeVertical) { 968 childHeightSize -= child.getMeasuredHeight(); 969 } else if (consumeHorizontal) { 970 childWidthSize -= child.getMeasuredWidth(); 971 } 972 } 973 } 974 } 975 976 mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY); 977 mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeightSize, MeasureSpec.EXACTLY); 978 979 // Make sure we have created all fragments that we need to have shown. 980 mInLayout = true; 981 populate(); 982 mInLayout = false; 983 984 // Page views next. 985 for (int i = 0; i < size; ++i) { 986 final View child = getChildAt(i); 987 if (child.getVisibility() != GONE) { 988 if (DEBUG) Log.v(TAG, "Measuring #" + i + " " + child 989 + ": " + mChildWidthMeasureSpec); 990 991 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 992 if (lp == null || !lp.isDecor) { 993 child.measure(mChildWidthMeasureSpec, mChildHeightMeasureSpec); 994 } 995 } 996 } 997 } 998 999 @Override 1000 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 1001 super.onSizeChanged(w, h, oldw, oldh); 1002 1003 // Make sure scroll position is set correctly. 1004 if (w != oldw) { 1005 recomputeScrollPosition(w, oldw, mPageMargin, mPageMargin); 1006 } 1007 } 1008 1009 private void recomputeScrollPosition(int width, int oldWidth, int margin, int oldMargin) { 1010 final int widthWithMargin = width + margin; 1011 if (oldWidth > 0) { 1012 final int oldScrollPos = getScrollX(); 1013 final int oldwwm = oldWidth + oldMargin; 1014 final int oldScrollItem = oldScrollPos / oldwwm; 1015 final float scrollOffset = (float) (oldScrollPos % oldwwm) / oldwwm; 1016 final int scrollPos = (int) ((oldScrollItem + scrollOffset) * widthWithMargin); 1017 scrollTo(scrollPos, getScrollY()); 1018 if (!mScroller.isFinished()) { 1019 // We now return to your regularly scheduled scroll, already in progress. 1020 final int newDuration = mScroller.getDuration() - mScroller.timePassed(); 1021 mScroller.startScroll(scrollPos, 0, mCurItem * widthWithMargin, 0, newDuration); 1022 } 1023 } else { 1024 int scrollPos = mCurItem * widthWithMargin; 1025 if (scrollPos != getScrollX()) { 1026 completeScroll(); 1027 scrollTo(scrollPos, getScrollY()); 1028 } 1029 } 1030 } 1031 1032 @Override 1033 protected void onLayout(boolean changed, int l, int t, int r, int b) { 1034 mInLayout = true; 1035 populate(); 1036 mInLayout = false; 1037 1038 final int count = getChildCount(); 1039 int width = r - l; 1040 int height = b - t; 1041 int paddingLeft = getPaddingLeft(); 1042 int paddingTop = getPaddingTop(); 1043 int paddingRight = getPaddingRight(); 1044 int paddingBottom = getPaddingBottom(); 1045 final int scrollX = getScrollX(); 1046 1047 int decorCount = 0; 1048 1049 for (int i = 0; i < count; i++) { 1050 final View child = getChildAt(i); 1051 if (child.getVisibility() != GONE) { 1052 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 1053 ItemInfo ii; 1054 int childLeft = 0; 1055 int childTop = 0; 1056 if (lp.isDecor) { 1057 final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK; 1058 final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK; 1059 switch (hgrav) { 1060 default: 1061 childLeft = paddingLeft; 1062 break; 1063 case Gravity.LEFT: 1064 childLeft = paddingLeft; 1065 paddingLeft += child.getMeasuredWidth(); 1066 break; 1067 case Gravity.CENTER_HORIZONTAL: 1068 childLeft = Math.max((width - child.getMeasuredWidth()) / 2, 1069 paddingLeft); 1070 break; 1071 case Gravity.RIGHT: 1072 childLeft = width - paddingRight - child.getMeasuredWidth(); 1073 paddingRight += child.getMeasuredWidth(); 1074 break; 1075 } 1076 switch (vgrav) { 1077 default: 1078 childTop = paddingTop; 1079 break; 1080 case Gravity.TOP: 1081 childTop = paddingTop; 1082 paddingTop += child.getMeasuredHeight(); 1083 break; 1084 case Gravity.CENTER_VERTICAL: 1085 childTop = Math.max((height - child.getMeasuredHeight()) / 2, 1086 paddingTop); 1087 break; 1088 case Gravity.BOTTOM: 1089 childTop = height - paddingBottom - child.getMeasuredHeight(); 1090 paddingBottom += child.getMeasuredHeight(); 1091 break; 1092 } 1093 childLeft += scrollX; 1094 decorCount++; 1095 } else if ((ii = infoForChild(child)) != null) { 1096 int loff = (width + mPageMargin) * ii.position; 1097 childLeft = paddingLeft + loff; 1098 childTop = paddingTop; 1099 if (DEBUG) Log.v(TAG, "Positioning #" + i + " " + child + " f=" + ii.object 1100 + ":" + childLeft + "," + childTop + " " + child.getMeasuredWidth() 1101 + "x" + child.getMeasuredHeight()); 1102 } 1103 child.layout(childLeft, childTop, 1104 childLeft + child.getMeasuredWidth(), 1105 childTop + child.getMeasuredHeight()); 1106 } 1107 } 1108 mTopPageBounds = paddingTop; 1109 mBottomPageBounds = height - paddingBottom; 1110 mDecorChildCount = decorCount; 1111 mFirstLayout = false; 1112 } 1113 1114 @Override 1115 public void computeScroll() { 1116 if (DEBUG) Log.i(TAG, "computeScroll: finished=" + mScroller.isFinished()); 1117 if (!mScroller.isFinished()) { 1118 if (mScroller.computeScrollOffset()) { 1119 if (DEBUG) Log.i(TAG, "computeScroll: still scrolling"); 1120 int oldX = getScrollX(); 1121 int oldY = getScrollY(); 1122 int x = mScroller.getCurrX(); 1123 int y = mScroller.getCurrY(); 1124 1125 if (oldX != x || oldY != y) { 1126 scrollTo(x, y); 1127 pageScrolled(x); 1128 } 1129 1130 // Keep on drawing until the animation has finished. 1131 invalidate(); 1132 return; 1133 } 1134 } 1135 1136 // Done with scroll, clean up state. 1137 completeScroll(); 1138 } 1139 1140 private void pageScrolled(int xpos) { 1141 final int widthWithMargin = getWidth() + mPageMargin; 1142 final int position = xpos / widthWithMargin; 1143 final int offsetPixels = xpos % widthWithMargin; 1144 final float offset = (float) offsetPixels / widthWithMargin; 1145 1146 mCalledSuper = false; 1147 onPageScrolled(position, offset, offsetPixels); 1148 if (!mCalledSuper) { 1149 throw new IllegalStateException( 1150 "onPageScrolled did not call superclass implementation"); 1151 } 1152 } 1153 1154 /** 1155 * This method will be invoked when the current page is scrolled, either as part 1156 * of a programmatically initiated smooth scroll or a user initiated touch scroll. 1157 * If you override this method you must call through to the superclass implementation 1158 * (e.g. super.onPageScrolled(position, offset, offsetPixels)) before onPageScrolled 1159 * returns. 1160 * 1161 * @param position Position index of the first page currently being displayed. 1162 * Page position+1 will be visible if positionOffset is nonzero. 1163 * @param offset Value from [0, 1) indicating the offset from the page at position. 1164 * @param offsetPixels Value in pixels indicating the offset from position. 1165 */ 1166 protected void onPageScrolled(int position, float offset, int offsetPixels) { 1167 // Offset any decor views if needed - keep them on-screen at all times. 1168 if (mDecorChildCount > 0) { 1169 final int scrollX = getScrollX(); 1170 int paddingLeft = getPaddingLeft(); 1171 int paddingRight = getPaddingRight(); 1172 final int width = getWidth(); 1173 final int childCount = getChildCount(); 1174 for (int i = 0; i < childCount; i++) { 1175 final View child = getChildAt(i); 1176 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 1177 if (!lp.isDecor) continue; 1178 1179 final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK; 1180 int childLeft = 0; 1181 switch (hgrav) { 1182 default: 1183 childLeft = paddingLeft; 1184 break; 1185 case Gravity.LEFT: 1186 childLeft = paddingLeft; 1187 paddingLeft += child.getWidth(); 1188 break; 1189 case Gravity.CENTER_HORIZONTAL: 1190 childLeft = Math.max((width - child.getMeasuredWidth()) / 2, 1191 paddingLeft); 1192 break; 1193 case Gravity.RIGHT: 1194 childLeft = width - paddingRight - child.getMeasuredWidth(); 1195 paddingRight += child.getMeasuredWidth(); 1196 break; 1197 } 1198 childLeft += scrollX; 1199 1200 final int childOffset = childLeft - child.getLeft(); 1201 if (childOffset != 0) { 1202 child.offsetLeftAndRight(childOffset); 1203 } 1204 } 1205 } 1206 1207 if (mOnPageChangeListener != null) { 1208 mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels); 1209 } 1210 if (mInternalPageChangeListener != null) { 1211 mInternalPageChangeListener.onPageScrolled(position, offset, offsetPixels); 1212 } 1213 mCalledSuper = true; 1214 } 1215 1216 private void completeScroll() { 1217 boolean needPopulate = mScrolling; 1218 if (needPopulate) { 1219 // Done with scroll, no longer want to cache view drawing. 1220 setScrollingCacheEnabled(false); 1221 mScroller.abortAnimation(); 1222 int oldX = getScrollX(); 1223 int oldY = getScrollY(); 1224 int x = mScroller.getCurrX(); 1225 int y = mScroller.getCurrY(); 1226 if (oldX != x || oldY != y) { 1227 scrollTo(x, y); 1228 } 1229 setScrollState(SCROLL_STATE_IDLE); 1230 } 1231 mPopulatePending = false; 1232 mScrolling = false; 1233 for (int i=0; i<mItems.size(); i++) { 1234 ItemInfo ii = mItems.get(i); 1235 if (ii.scrolling) { 1236 needPopulate = true; 1237 ii.scrolling = false; 1238 } 1239 } 1240 if (needPopulate) { 1241 populate(); 1242 } 1243 } 1244 1245 @Override 1246 public boolean onInterceptTouchEvent(MotionEvent ev) { 1247 /* 1248 * This method JUST determines whether we want to intercept the motion. 1249 * If we return true, onMotionEvent will be called and we do the actual 1250 * scrolling there. 1251 */ 1252 1253 final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; 1254 1255 // Always take care of the touch gesture being complete. 1256 if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { 1257 // Release the drag. 1258 if (DEBUG) Log.v(TAG, "Intercept done!"); 1259 mIsBeingDragged = false; 1260 mIsUnableToDrag = false; 1261 mActivePointerId = INVALID_POINTER; 1262 return false; 1263 } 1264 1265 // Nothing more to do here if we have decided whether or not we 1266 // are dragging. 1267 if (action != MotionEvent.ACTION_DOWN) { 1268 if (mIsBeingDragged) { 1269 if (DEBUG) Log.v(TAG, "Intercept returning true!"); 1270 return true; 1271 } 1272 if (mIsUnableToDrag) { 1273 if (DEBUG) Log.v(TAG, "Intercept returning false!"); 1274 return false; 1275 } 1276 } 1277 1278 switch (action) { 1279 case MotionEvent.ACTION_MOVE: { 1280 /* 1281 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check 1282 * whether the user has moved far enough from his original down touch. 1283 */ 1284 1285 /* 1286 * Locally do absolute value. mLastMotionY is set to the y value 1287 * of the down event. 1288 */ 1289 final int activePointerId = mActivePointerId; 1290 if (activePointerId == INVALID_POINTER) { 1291 // If we don't have a valid id, the touch down wasn't on content. 1292 break; 1293 } 1294 1295 final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId); 1296 final float x = MotionEventCompat.getX(ev, pointerIndex); 1297 final float dx = x - mLastMotionX; 1298 final float xDiff = Math.abs(dx); 1299 final float y = MotionEventCompat.getY(ev, pointerIndex); 1300 final float yDiff = Math.abs(y - mLastMotionY); 1301 final int scrollX = getScrollX(); 1302 final boolean atEdge = (dx > 0 && scrollX == 0) || (dx < 0 && mAdapter != null && 1303 scrollX >= (mAdapter.getCount() - 1) * getWidth() - 1); 1304 if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); 1305 1306 if (canScroll(this, false, (int) dx, (int) x, (int) y)) { 1307 // Nested view has scrollable area under this point. Let it be handled there. 1308 mInitialMotionX = mLastMotionX = x; 1309 mLastMotionY = y; 1310 return false; 1311 } 1312 if (xDiff > mTouchSlop && xDiff > yDiff) { 1313 if (DEBUG) Log.v(TAG, "Starting drag!"); 1314 mIsBeingDragged = true; 1315 setScrollState(SCROLL_STATE_DRAGGING); 1316 mLastMotionX = x; 1317 setScrollingCacheEnabled(true); 1318 } else { 1319 if (yDiff > mTouchSlop) { 1320 // The finger has moved enough in the vertical 1321 // direction to be counted as a drag... abort 1322 // any attempt to drag horizontally, to work correctly 1323 // with children that have scrolling containers. 1324 if (DEBUG) Log.v(TAG, "Starting unable to drag!"); 1325 mIsUnableToDrag = true; 1326 } 1327 } 1328 break; 1329 } 1330 1331 case MotionEvent.ACTION_DOWN: { 1332 /* 1333 * Remember location of down touch. 1334 * ACTION_DOWN always refers to pointer index 0. 1335 */ 1336 mLastMotionX = mInitialMotionX = ev.getX(); 1337 mLastMotionY = ev.getY(); 1338 mActivePointerId = MotionEventCompat.getPointerId(ev, 0); 1339 1340 if (mScrollState == SCROLL_STATE_SETTLING) { 1341 // Let the user 'catch' the pager as it animates. 1342 mIsBeingDragged = true; 1343 mIsUnableToDrag = false; 1344 setScrollState(SCROLL_STATE_DRAGGING); 1345 } else { 1346 completeScroll(); 1347 mIsBeingDragged = false; 1348 mIsUnableToDrag = false; 1349 } 1350 1351 if (DEBUG) Log.v(TAG, "Down at " + mLastMotionX + "," + mLastMotionY 1352 + " mIsBeingDragged=" + mIsBeingDragged 1353 + "mIsUnableToDrag=" + mIsUnableToDrag); 1354 break; 1355 } 1356 1357 case MotionEventCompat.ACTION_POINTER_UP: 1358 onSecondaryPointerUp(ev); 1359 break; 1360 } 1361 1362 /* 1363 * The only time we want to intercept motion events is if we are in the 1364 * drag mode. 1365 */ 1366 return mIsBeingDragged; 1367 } 1368 1369 @Override 1370 public boolean onTouchEvent(MotionEvent ev) { 1371 if (mFakeDragging) { 1372 // A fake drag is in progress already, ignore this real one 1373 // but still eat the touch events. 1374 // (It is likely that the user is multi-touching the screen.) 1375 return true; 1376 } 1377 1378 if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) { 1379 // Don't handle edge touches immediately -- they may actually belong to one of our 1380 // descendants. 1381 return false; 1382 } 1383 1384 if (mAdapter == null || mAdapter.getCount() == 0) { 1385 // Nothing to present or scroll; nothing to touch. 1386 return false; 1387 } 1388 1389 if (mVelocityTracker == null) { 1390 mVelocityTracker = VelocityTracker.obtain(); 1391 } 1392 mVelocityTracker.addMovement(ev); 1393 1394 final int action = ev.getAction(); 1395 boolean needsInvalidate = false; 1396 1397 switch (action & MotionEventCompat.ACTION_MASK) { 1398 case MotionEvent.ACTION_DOWN: { 1399 /* 1400 * If being flinged and user touches, stop the fling. isFinished 1401 * will be false if being flinged. 1402 */ 1403 completeScroll(); 1404 1405 // Remember where the motion event started 1406 mLastMotionX = mInitialMotionX = ev.getX(); 1407 mActivePointerId = MotionEventCompat.getPointerId(ev, 0); 1408 break; 1409 } 1410 case MotionEvent.ACTION_MOVE: 1411 if (!mIsBeingDragged) { 1412 final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); 1413 final float x = MotionEventCompat.getX(ev, pointerIndex); 1414 final float xDiff = Math.abs(x - mLastMotionX); 1415 final float y = MotionEventCompat.getY(ev, pointerIndex); 1416 final float yDiff = Math.abs(y - mLastMotionY); 1417 if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); 1418 if (xDiff > mTouchSlop && xDiff > yDiff) { 1419 if (DEBUG) Log.v(TAG, "Starting drag!"); 1420 mIsBeingDragged = true; 1421 mLastMotionX = x; 1422 setScrollState(SCROLL_STATE_DRAGGING); 1423 setScrollingCacheEnabled(true); 1424 } 1425 } 1426 if (mIsBeingDragged) { 1427 // Scroll to follow the motion event 1428 final int activePointerIndex = MotionEventCompat.findPointerIndex( 1429 ev, mActivePointerId); 1430 final float x = MotionEventCompat.getX(ev, activePointerIndex); 1431 final float deltaX = mLastMotionX - x; 1432 mLastMotionX = x; 1433 float oldScrollX = getScrollX(); 1434 float scrollX = oldScrollX + deltaX; 1435 final int width = getWidth(); 1436 final int widthWithMargin = width + mPageMargin; 1437 1438 final int lastItemIndex = mAdapter.getCount() - 1; 1439 final float leftBound = Math.max(0, (mCurItem - 1) * widthWithMargin); 1440 final float rightBound = 1441 Math.min(mCurItem + 1, lastItemIndex) * widthWithMargin; 1442 if (scrollX < leftBound) { 1443 if (leftBound == 0) { 1444 float over = -scrollX; 1445 needsInvalidate = mLeftEdge.onPull(over / width); 1446 } 1447 scrollX = leftBound; 1448 } else if (scrollX > rightBound) { 1449 if (rightBound == lastItemIndex * widthWithMargin) { 1450 float over = scrollX - rightBound; 1451 needsInvalidate = mRightEdge.onPull(over / width); 1452 } 1453 scrollX = rightBound; 1454 } 1455 // Don't lose the rounded component 1456 mLastMotionX += scrollX - (int) scrollX; 1457 scrollTo((int) scrollX, getScrollY()); 1458 pageScrolled((int) scrollX); 1459 } 1460 break; 1461 case MotionEvent.ACTION_UP: 1462 if (mIsBeingDragged) { 1463 final VelocityTracker velocityTracker = mVelocityTracker; 1464 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 1465 int initialVelocity = (int) VelocityTrackerCompat.getXVelocity( 1466 velocityTracker, mActivePointerId); 1467 mPopulatePending = true; 1468 final int widthWithMargin = getWidth() + mPageMargin; 1469 final int scrollX = getScrollX(); 1470 final int currentPage = scrollX / widthWithMargin; 1471 int nextPage = initialVelocity > 0 ? currentPage : currentPage + 1; 1472 setCurrentItemInternal(nextPage, true, true, initialVelocity); 1473 1474 mActivePointerId = INVALID_POINTER; 1475 endDrag(); 1476 needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease(); 1477 } 1478 break; 1479 case MotionEvent.ACTION_CANCEL: 1480 if (mIsBeingDragged) { 1481 setCurrentItemInternal(mCurItem, true, true); 1482 mActivePointerId = INVALID_POINTER; 1483 endDrag(); 1484 needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease(); 1485 } 1486 break; 1487 case MotionEventCompat.ACTION_POINTER_DOWN: { 1488 final int index = MotionEventCompat.getActionIndex(ev); 1489 final float x = MotionEventCompat.getX(ev, index); 1490 mLastMotionX = x; 1491 mActivePointerId = MotionEventCompat.getPointerId(ev, index); 1492 break; 1493 } 1494 case MotionEventCompat.ACTION_POINTER_UP: 1495 onSecondaryPointerUp(ev); 1496 mLastMotionX = MotionEventCompat.getX(ev, 1497 MotionEventCompat.findPointerIndex(ev, mActivePointerId)); 1498 break; 1499 } 1500 if (needsInvalidate) { 1501 invalidate(); 1502 } 1503 return true; 1504 } 1505 1506 @Override 1507 public void draw(Canvas canvas) { 1508 super.draw(canvas); 1509 boolean needsInvalidate = false; 1510 1511 final int overScrollMode = ViewCompat.getOverScrollMode(this); 1512 if (overScrollMode == ViewCompat.OVER_SCROLL_ALWAYS || 1513 (overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS && 1514 mAdapter != null && mAdapter.getCount() > 1)) { 1515 if (!mLeftEdge.isFinished()) { 1516 final int restoreCount = canvas.save(); 1517 final int height = getHeight() - getPaddingTop() - getPaddingBottom(); 1518 1519 canvas.rotate(270); 1520 canvas.translate(-height + getPaddingTop(), 0); 1521 mLeftEdge.setSize(height, getWidth()); 1522 needsInvalidate |= mLeftEdge.draw(canvas); 1523 canvas.restoreToCount(restoreCount); 1524 } 1525 if (!mRightEdge.isFinished()) { 1526 final int restoreCount = canvas.save(); 1527 final int width = getWidth(); 1528 final int height = getHeight() - getPaddingTop() - getPaddingBottom(); 1529 final int itemCount = mAdapter != null ? mAdapter.getCount() : 1; 1530 1531 canvas.rotate(90); 1532 canvas.translate(-getPaddingTop(), 1533 -itemCount * (width + mPageMargin) + mPageMargin); 1534 mRightEdge.setSize(height, width); 1535 needsInvalidate |= mRightEdge.draw(canvas); 1536 canvas.restoreToCount(restoreCount); 1537 } 1538 } else { 1539 mLeftEdge.finish(); 1540 mRightEdge.finish(); 1541 } 1542 1543 if (needsInvalidate) { 1544 // Keep animating 1545 invalidate(); 1546 } 1547 } 1548 1549 @Override 1550 protected void onDraw(Canvas canvas) { 1551 super.onDraw(canvas); 1552 1553 // Draw the margin drawable if needed. 1554 if (mPageMargin > 0 && mMarginDrawable != null) { 1555 final int scrollX = getScrollX(); 1556 final int width = getWidth(); 1557 final int offset = scrollX % (width + mPageMargin); 1558 if (offset != 0) { 1559 // Pages fit completely when settled; we only need to draw when in between 1560 final int left = scrollX - offset + width; 1561 mMarginDrawable.setBounds(left, mTopPageBounds, left + mPageMargin, 1562 mBottomPageBounds); 1563 mMarginDrawable.draw(canvas); 1564 } 1565 } 1566 } 1567 1568 /** 1569 * Start a fake drag of the pager. 1570 * 1571 * <p>A fake drag can be useful if you want to synchronize the motion of the ViewPager 1572 * with the touch scrolling of another view, while still letting the ViewPager 1573 * control the snapping motion and fling behavior. (e.g. parallax-scrolling tabs.) 1574 * Call {@link #fakeDragBy(float)} to simulate the actual drag motion. Call 1575 * {@link #endFakeDrag()} to complete the fake drag and fling as necessary. 1576 * 1577 * <p>During a fake drag the ViewPager will ignore all touch events. If a real drag 1578 * is already in progress, this method will return false. 1579 * 1580 * @return true if the fake drag began successfully, false if it could not be started. 1581 * 1582 * @see #fakeDragBy(float) 1583 * @see #endFakeDrag() 1584 */ 1585 public boolean beginFakeDrag() { 1586 if (mIsBeingDragged) { 1587 return false; 1588 } 1589 mFakeDragging = true; 1590 setScrollState(SCROLL_STATE_DRAGGING); 1591 mInitialMotionX = mLastMotionX = 0; 1592 if (mVelocityTracker == null) { 1593 mVelocityTracker = VelocityTracker.obtain(); 1594 } else { 1595 mVelocityTracker.clear(); 1596 } 1597 final long time = SystemClock.uptimeMillis(); 1598 final MotionEvent ev = MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, 0, 0, 0); 1599 mVelocityTracker.addMovement(ev); 1600 ev.recycle(); 1601 mFakeDragBeginTime = time; 1602 return true; 1603 } 1604 1605 /** 1606 * End a fake drag of the pager. 1607 * 1608 * @see #beginFakeDrag() 1609 * @see #fakeDragBy(float) 1610 */ 1611 public void endFakeDrag() { 1612 if (!mFakeDragging) { 1613 throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first."); 1614 } 1615 1616 final VelocityTracker velocityTracker = mVelocityTracker; 1617 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 1618 int initialVelocity = (int)VelocityTrackerCompat.getYVelocity( 1619 velocityTracker, mActivePointerId); 1620 mPopulatePending = true; 1621 if ((Math.abs(initialVelocity) > mMinimumVelocity) 1622 || Math.abs(mInitialMotionX-mLastMotionX) >= (getWidth()/3)) { 1623 if (mLastMotionX > mInitialMotionX) { 1624 setCurrentItemInternal(mCurItem-1, true, true); 1625 } else { 1626 setCurrentItemInternal(mCurItem+1, true, true); 1627 } 1628 } else { 1629 setCurrentItemInternal(mCurItem, true, true); 1630 } 1631 endDrag(); 1632 1633 mFakeDragging = false; 1634 } 1635 1636 /** 1637 * Fake drag by an offset in pixels. You must have called {@link #beginFakeDrag()} first. 1638 * 1639 * @param xOffset Offset in pixels to drag by. 1640 * @see #beginFakeDrag() 1641 * @see #endFakeDrag() 1642 */ 1643 public void fakeDragBy(float xOffset) { 1644 if (!mFakeDragging) { 1645 throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first."); 1646 } 1647 1648 mLastMotionX += xOffset; 1649 float scrollX = getScrollX() - xOffset; 1650 final int width = getWidth(); 1651 final int widthWithMargin = width + mPageMargin; 1652 1653 final float leftBound = Math.max(0, (mCurItem - 1) * widthWithMargin); 1654 final float rightBound = 1655 Math.min(mCurItem + 1, mAdapter.getCount() - 1) * widthWithMargin; 1656 if (scrollX < leftBound) { 1657 scrollX = leftBound; 1658 } else if (scrollX > rightBound) { 1659 scrollX = rightBound; 1660 } 1661 // Don't lose the rounded component 1662 mLastMotionX += scrollX - (int) scrollX; 1663 scrollTo((int) scrollX, getScrollY()); 1664 pageScrolled((int) scrollX); 1665 1666 // Synthesize an event for the VelocityTracker. 1667 final long time = SystemClock.uptimeMillis(); 1668 final MotionEvent ev = MotionEvent.obtain(mFakeDragBeginTime, time, MotionEvent.ACTION_MOVE, 1669 mLastMotionX, 0, 0); 1670 mVelocityTracker.addMovement(ev); 1671 ev.recycle(); 1672 } 1673 1674 /** 1675 * Returns true if a fake drag is in progress. 1676 * 1677 * @return true if currently in a fake drag, false otherwise. 1678 * 1679 * @see #beginFakeDrag() 1680 * @see #fakeDragBy(float) 1681 * @see #endFakeDrag() 1682 */ 1683 public boolean isFakeDragging() { 1684 return mFakeDragging; 1685 } 1686 1687 private void onSecondaryPointerUp(MotionEvent ev) { 1688 final int pointerIndex = MotionEventCompat.getActionIndex(ev); 1689 final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); 1690 if (pointerId == mActivePointerId) { 1691 // This was our active pointer going up. Choose a new 1692 // active pointer and adjust accordingly. 1693 final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 1694 mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex); 1695 mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); 1696 if (mVelocityTracker != null) { 1697 mVelocityTracker.clear(); 1698 } 1699 } 1700 } 1701 1702 private void endDrag() { 1703 mIsBeingDragged = false; 1704 mIsUnableToDrag = false; 1705 1706 if (mVelocityTracker != null) { 1707 mVelocityTracker.recycle(); 1708 mVelocityTracker = null; 1709 } 1710 } 1711 1712 private void setScrollingCacheEnabled(boolean enabled) { 1713 if (mScrollingCacheEnabled != enabled) { 1714 mScrollingCacheEnabled = enabled; 1715 if (USE_CACHE) { 1716 final int size = getChildCount(); 1717 for (int i = 0; i < size; ++i) { 1718 final View child = getChildAt(i); 1719 if (child.getVisibility() != GONE) { 1720 child.setDrawingCacheEnabled(enabled); 1721 } 1722 } 1723 } 1724 } 1725 } 1726 1727 /** 1728 * Tests scrollability within child views of v given a delta of dx. 1729 * 1730 * @param v View to test for horizontal scrollability 1731 * @param checkV Whether the view v passed should itself be checked for scrollability (true), 1732 * or just its children (false). 1733 * @param dx Delta scrolled in pixels 1734 * @param x X coordinate of the active touch point 1735 * @param y Y coordinate of the active touch point 1736 * @return true if child views of v can be scrolled by delta of dx. 1737 */ 1738 protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) { 1739 if (v instanceof ViewGroup) { 1740 final ViewGroup group = (ViewGroup) v; 1741 final int scrollX = v.getScrollX(); 1742 final int scrollY = v.getScrollY(); 1743 final int count = group.getChildCount(); 1744 // Count backwards - let topmost views consume scroll distance first. 1745 for (int i = count - 1; i >= 0; i--) { 1746 // TODO: Add versioned support here for transformed views. 1747 // This will not work for transformed views in Honeycomb+ 1748 final View child = group.getChildAt(i); 1749 if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() && 1750 y + scrollY >= child.getTop() && y + scrollY < child.getBottom() && 1751 canScroll(child, true, dx, x + scrollX - child.getLeft(), 1752 y + scrollY - child.getTop())) { 1753 return true; 1754 } 1755 } 1756 } 1757 1758 return checkV && ViewCompat.canScrollHorizontally(v, -dx); 1759 } 1760 1761 @Override 1762 public boolean dispatchKeyEvent(KeyEvent event) { 1763 // Let the focused view and/or our descendants get the key first 1764 return super.dispatchKeyEvent(event) || executeKeyEvent(event); 1765 } 1766 1767 /** 1768 * You can call this function yourself to have the scroll view perform 1769 * scrolling from a key event, just as if the event had been dispatched to 1770 * it by the view hierarchy. 1771 * 1772 * @param event The key event to execute. 1773 * @return Return true if the event was handled, else false. 1774 */ 1775 public boolean executeKeyEvent(KeyEvent event) { 1776 boolean handled = false; 1777 if (event.getAction() == KeyEvent.ACTION_DOWN) { 1778 switch (event.getKeyCode()) { 1779 case KeyEvent.KEYCODE_DPAD_LEFT: 1780 handled = arrowScroll(FOCUS_LEFT); 1781 break; 1782 case KeyEvent.KEYCODE_DPAD_RIGHT: 1783 handled = arrowScroll(FOCUS_RIGHT); 1784 break; 1785 case KeyEvent.KEYCODE_TAB: 1786 if (KeyEventCompat.hasNoModifiers(event)) { 1787 handled = arrowScroll(FOCUS_FORWARD); 1788 } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) { 1789 handled = arrowScroll(FOCUS_BACKWARD); 1790 } 1791 break; 1792 } 1793 } 1794 return handled; 1795 } 1796 1797 public boolean arrowScroll(int direction) { 1798 View currentFocused = findFocus(); 1799 if (currentFocused == this) currentFocused = null; 1800 1801 boolean handled = false; 1802 1803 View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, 1804 direction); 1805 if (nextFocused != null && nextFocused != currentFocused) { 1806 if (direction == View.FOCUS_LEFT) { 1807 // If there is nothing to the left, or this is causing us to 1808 // jump to the right, then what we really want to do is page left. 1809 if (currentFocused != null && nextFocused.getLeft() >= currentFocused.getLeft()) { 1810 handled = pageLeft(); 1811 } else { 1812 handled = nextFocused.requestFocus(); 1813 } 1814 } else if (direction == View.FOCUS_RIGHT) { 1815 // If there is nothing to the right, or this is causing us to 1816 // jump to the left, then what we really want to do is page right. 1817 if (currentFocused != null && nextFocused.getLeft() <= currentFocused.getLeft()) { 1818 handled = pageRight(); 1819 } else { 1820 handled = nextFocused.requestFocus(); 1821 } 1822 } 1823 } else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) { 1824 // Trying to move left and nothing there; try to page. 1825 handled = pageLeft(); 1826 } else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) { 1827 // Trying to move right and nothing there; try to page. 1828 handled = pageRight(); 1829 } 1830 if (handled) { 1831 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction)); 1832 } 1833 return handled; 1834 } 1835 1836 boolean pageLeft() { 1837 if (mCurItem > 0) { 1838 setCurrentItem(mCurItem-1, true); 1839 return true; 1840 } 1841 return false; 1842 } 1843 1844 boolean pageRight() { 1845 if (mAdapter != null && mCurItem < (mAdapter.getCount()-1)) { 1846 setCurrentItem(mCurItem+1, true); 1847 return true; 1848 } 1849 return false; 1850 } 1851 1852 /** 1853 * We only want the current page that is being shown to be focusable. 1854 */ 1855 @Override 1856 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 1857 final int focusableCount = views.size(); 1858 1859 final int descendantFocusability = getDescendantFocusability(); 1860 1861 if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) { 1862 for (int i = 0; i < getChildCount(); i++) { 1863 final View child = getChildAt(i); 1864 if (child.getVisibility() == VISIBLE) { 1865 ItemInfo ii = infoForChild(child); 1866 if (ii != null && ii.position == mCurItem) { 1867 child.addFocusables(views, direction, focusableMode); 1868 } 1869 } 1870 } 1871 } 1872 1873 // we add ourselves (if focusable) in all cases except for when we are 1874 // FOCUS_AFTER_DESCENDANTS and there are some descendants focusable. this is 1875 // to avoid the focus search finding layouts when a more precise search 1876 // among the focusable children would be more interesting. 1877 if ( 1878 descendantFocusability != FOCUS_AFTER_DESCENDANTS || 1879 // No focusable descendants 1880 (focusableCount == views.size())) { 1881 // Note that we can't call the superclass here, because it will 1882 // add all views in. So we need to do the same thing View does. 1883 if (!isFocusable()) { 1884 return; 1885 } 1886 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && 1887 isInTouchMode() && !isFocusableInTouchMode()) { 1888 return; 1889 } 1890 if (views != null) { 1891 views.add(this); 1892 } 1893 } 1894 } 1895 1896 /** 1897 * We only want the current page that is being shown to be touchable. 1898 */ 1899 @Override 1900 public void addTouchables(ArrayList<View> views) { 1901 // Note that we don't call super.addTouchables(), which means that 1902 // we don't call View.addTouchables(). This is okay because a ViewPager 1903 // is itself not touchable. 1904 for (int i = 0; i < getChildCount(); i++) { 1905 final View child = getChildAt(i); 1906 if (child.getVisibility() == VISIBLE) { 1907 ItemInfo ii = infoForChild(child); 1908 if (ii != null && ii.position == mCurItem) { 1909 child.addTouchables(views); 1910 } 1911 } 1912 } 1913 } 1914 1915 /** 1916 * We only want the current page that is being shown to be focusable. 1917 */ 1918 @Override 1919 protected boolean onRequestFocusInDescendants(int direction, 1920 Rect previouslyFocusedRect) { 1921 int index; 1922 int increment; 1923 int end; 1924 int count = getChildCount(); 1925 if ((direction & FOCUS_FORWARD) != 0) { 1926 index = 0; 1927 increment = 1; 1928 end = count; 1929 } else { 1930 index = count - 1; 1931 increment = -1; 1932 end = -1; 1933 } 1934 for (int i = index; i != end; i += increment) { 1935 View child = getChildAt(i); 1936 if (child.getVisibility() == VISIBLE) { 1937 ItemInfo ii = infoForChild(child); 1938 if (ii != null && ii.position == mCurItem) { 1939 if (child.requestFocus(direction, previouslyFocusedRect)) { 1940 return true; 1941 } 1942 } 1943 } 1944 } 1945 return false; 1946 } 1947 1948 @Override 1949 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 1950 // ViewPagers should only report accessibility info for the current page, 1951 // otherwise things get very confusing. 1952 1953 // TODO: Should this note something about the paging container? 1954 1955 final int childCount = getChildCount(); 1956 for (int i = 0; i < childCount; i++) { 1957 final View child = getChildAt(i); 1958 if (child.getVisibility() == VISIBLE) { 1959 final ItemInfo ii = infoForChild(child); 1960 if (ii != null && ii.position == mCurItem && 1961 child.dispatchPopulateAccessibilityEvent(event)) { 1962 return true; 1963 } 1964 } 1965 } 1966 1967 return false; 1968 } 1969 1970 @Override 1971 protected ViewGroup.LayoutParams generateDefaultLayoutParams() { 1972 return new LayoutParams(); 1973 } 1974 1975 @Override 1976 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { 1977 return generateDefaultLayoutParams(); 1978 } 1979 1980 @Override 1981 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { 1982 return p instanceof LayoutParams && super.checkLayoutParams(p); 1983 } 1984 1985 @Override 1986 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { 1987 return new LayoutParams(getContext(), attrs); 1988 } 1989 1990 private class PagerObserver extends DataSetObserver { 1991 @Override 1992 public void onChanged() { 1993 dataSetChanged(); 1994 } 1995 @Override 1996 public void onInvalidated() { 1997 dataSetChanged(); 1998 } 1999 } 2000 2001 public static class LayoutParams extends ViewGroup.LayoutParams { 2002 /** 2003 * true if this view is a decoration on the pager itself and not 2004 * a view supplied by the adapter. 2005 */ 2006 public boolean isDecor; 2007 2008 public int gravity; 2009 2010 public LayoutParams() { 2011 super(FILL_PARENT, FILL_PARENT); 2012 } 2013 2014 public LayoutParams(Context context, AttributeSet attrs) { 2015 super(context, attrs); 2016 2017 final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS); 2018 gravity = a.getInteger(0, Gravity.NO_GRAVITY); 2019 a.recycle(); 2020 } 2021 } 2022} 2023