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