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