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