转自:http://blog.csdn.net/yymonkeydo/article/details/47012153

在github中找到了一个可以垂直翻页的ViewPager,但是只能使用的是他写的pagerAdapter的子类,为了,让自己的项目中也可以使用v4和v13的适配器,自己就改动了一点点,代码如下:

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

适配器代码:

[java]  view plain copy print ?
  1. package com.yymonkeydo.androiddemo;
  2. import java.util.List;
  3. import android.support.v4.app.Fragment;
  4. import android.support.v4.app.FragmentManager;
  5. import android.support.v4.app.FragmentStatePagerAdapter;
  6. public class VerticalPagerAdapter extends FragmentStatePagerAdapter {
  7. private List<Fragment> mData;
  8. public VerticalPagerAdapter(FragmentManager fm, List<Fragment> data) {
  9. super(fm);
  10. mData = data;
  11. }
  12. @Override
  13. public Fragment getItem(int position) {
  14. return mData.get(position);
  15. }
  16. @Override
  17. public int getCount() {
  18. return mData == null ? 0 : mData.size();
  19. }
  20. }

Fragment代码:

[java]  view plain copy print ?
  1. package com.yymonkeydo.androiddemo;
  2. import android.os.Bundle;
  3. import android.support.v4.app.Fragment;
  4. import android.view.Gravity;
  5. import android.view.LayoutInflater;
  6. import android.view.View;
  7. import android.view.ViewGroup;
  8. import android.widget.Button;
  9. public class MyFragment extends Fragment {
  10. @Override
  11. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  12. Bundle savedInstanceState) {
  13. Button btn = new Button(getActivity());
  14. btn.setText("TxT");
  15. btn.setGravity(Gravity.CENTER);
  16. return btn;
  17. }
  18. }

Activity:

[java]  view plain copy print ?
  1. package com.yymonkeydo.androiddemo;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import com.yymonkeydo.androiddemo.R;
  5. import android.os.Bundle;
  6. import android.support.v4.app.Fragment;
  7. import android.support.v4.app.FragmentActivity;
  8. public class MainActivity extends FragmentActivity {
  9. private VerticalViewPager mViewPager;
  10. private VerticalPagerAdapter mAdapter;
  11. private List<Fragment> mData;
  12. @Override
  13. protected void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.activity_main);
  16. mViewPager = (VerticalViewPager) findViewById(R.id.viewpager);
  17. mData = new ArrayList<Fragment>();
  18. mData.add(new MyFragment());
  19. mData.add(new MyFragment());
  20. mData.add(new MyFragment());
  21. mAdapter = new VerticalPagerAdapter(getSupportFragmentManager(), mData);
  22. mViewPager.setAdapter(mAdapter);
  23. }
  24. }

上面代码直接用回报错,把 VerticalViewPager 类中的 FloatMath改成Math就行了。

垂直翻页的Viewpager 兼容华为手机相关推荐

  1. 自定义View之垂直翻页公告

    俗名:垂直跑马灯 学名:垂直翻页公告 动态效果图: GitHub开源地址 APK下载地址 使用 Gradle: compile 'com.sunfusheng:marqueeview:1.0.0' 属 ...

  2. Android中为PopupWindow设置半透明背景的方案(兼容华为手机)

    原文地址:https://blog.csdn.net/biaobiao1217/article/details/51438552 android中为PopupWindow设置半透明背景已经是老生常谈的 ...

  3. HTML垂直翻页公告

    发现 今天看到了一个Android的自定义View垂直翻页公告,感觉挺好的,运行的动图让我搬过来了,顺便感谢一下写这个Android公告的作者的分享. 由于这两天在做一个聊天室的项目,看到这个之后,决 ...

  4. android垂直公告,【Android之垂直翻页公告】

    该源码是android studio版本,本文最后提供的是eclipse版本,以供大家学习参考. 效果如图: 源码分析: 核心类:MarqueeView.java 核心思想是根据公告内容的数量动态生成 ...

  5. 【Android 基础知识】翻页类视图 ViewPager

    文章目录 1.翻页视图 ViewPager 2.翻页标题栏 PagerTitleStrip/PagerTabStrip 1.翻页视图 ViewPager 对于 ViewPager 来说,一个页面就是一 ...

  6. 移动端项目中使用rem布局,华为手机不兼容。

    在上一次做人脸审核的项目(h5)的时候,需要适配各种设备手机的屏幕, 刚开始的时候使用的那套(不兼容华为)rem的计算逻辑,在测试的时候却发现在华为一些部分机型不适配,超出了屏幕. 后来在网上查阅资料 ...

  7. Android开发笔记(一百七十二)第二代翻页视图ViewPager2

    正如RecyclerView横空出世取代ListView和GridView那样,Android也推出了二代翻页视图ViewPager2,打算替换原来的翻页视图ViewPager.与ViewPager相 ...

  8. 怎么开启华为手机隐藏功能

    功能一:速记 我们还可以为备忘录开启速记功能,在没有打开备忘录软件的时候,能够快速打开笔记编辑的界面. 操作步骤:打开备忘录,找到右上角的三个点,会弹出一个小窗,然后我们选择"设置" ...

  9. Android开发笔记(十八)书籍翻页动画PageAnimation

    前面几节的动画都算简单,本文就介绍一个复杂点的动画--书籍翻页动画.Android有自带的翻页动画ViewPager,不过ViewPager只实现了平移效果.即便使用补间组合动画或者属性动画,也只是把 ...

最新文章

  1. selenium 实现网页截图
  2. 与其倒推以前不如推到重建
  3. 使用supervisor支持Python3程序 (解决找不到Module的问题)
  4. Selenium 自动化测试之道--Maven-TestNG
  5. [云炬python3玩转机器学习笔记] 3-2 Jupter Notebook魔法命令
  6. IntelliJ IDEA中文乱码问题
  7. 打入硅谷的局外人|Decode the Week
  8. 微软发布VS Code Jupyter插件!不止Python!多语言的Jupyter Notebook支持来了!
  9. linux java性能监控工具_Linux实时监控工具Nmon使用
  10. python3.6安装dlib,一直不成功的解决办法
  11. 农村金融大变革,央行要给农民发钱了!
  12. ADS仿真设计AB类射频功率放大器
  13. 黑马程序员-IT学生解惑真经-想做程序员或者正在迟疑的同学可以看一下,很有帮助的一篇文章
  14. 全球最大湾区|微信大数据:《粤港澳大湾区智慧生活圈报告》
  15. 武汉音乐学院计算机音乐作曲,武汉音乐学院作曲系6部学生作品入围2019年中国大学生计算机设计大赛决赛...
  16. 高速串行总线设计基础(七)揭秘SERDES高速面纱之时钟校正与通道绑定技术
  17. 安装并测试Gitweb
  18. React 接入 Ueditor + xiumi
  19. 转一次排障经历以供学习
  20. 视频正在os x使用中_如何在OS X中使用家长控制来保护孩子

热门文章

  1. 高密度 PCB 线路板设计中的过孔知识
  2. 幼儿园计算机网络教室工作计划,2020年幼儿园电教工作计划
  3. 计算机专业的考mem还是mba,还在纠结考MBA还是MEM?快来看它们的区别
  4. 视频分析模型(行为识别):C3D
  5. vps2routeros
  6. 手机号短信验证码接口
  7. 34. java8新特性
  8. linux下安装mysql8(基于yum安装和mysql安装包离线安装两种方式)
  9. 如何开通阿里云服务器的HTTPS功能?
  10. Baidu Story(百度传奇)