ViewPager.java revision 862ffa0efd58922b8ec119bf6fa6695c316423f7
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                } else if ((ii = infoForChild(child)) != null) {
1097                    int loff = (width + mPageMargin) * ii.position;
1098                    childLeft = paddingLeft + loff;
1099                    childTop = paddingTop;
1100                    if (DEBUG) Log.v(TAG, "Positioning #" + i + " " + child + " f=" + ii.object
1101                            + ":" + childLeft + "," + childTop + " " + child.getMeasuredWidth()
1102                            + "x" + child.getMeasuredHeight());
1103                }
1104                child.layout(childLeft, childTop,
1105                        childLeft + child.getMeasuredWidth(),
1106                        childTop + child.getMeasuredHeight());
1107            }
1108        }
1109        mTopPageBounds = paddingTop;
1110        mBottomPageBounds = height - paddingBottom;
1111        mDecorChildCount = decorCount;
1112        mFirstLayout = false;
1113    }
1114
1115    @Override
1116    public void computeScroll() {
1117        if (DEBUG) Log.i(TAG, "computeScroll: finished=" + mScroller.isFinished());
1118        if (!mScroller.isFinished()) {
1119            if (mScroller.computeScrollOffset()) {
1120                if (DEBUG) Log.i(TAG, "computeScroll: still scrolling");
1121                int oldX = getScrollX();
1122                int oldY = getScrollY();
1123                int x = mScroller.getCurrX();
1124                int y = mScroller.getCurrY();
1125
1126                if (oldX != x || oldY != y) {
1127                    scrollTo(x, y);
1128                    pageScrolled(x);
1129                }
1130
1131                // Keep on drawing until the animation has finished.
1132                invalidate();
1133                return;
1134            }
1135        }
1136
1137        // Done with scroll, clean up state.
1138        completeScroll();
1139    }
1140
1141    private void pageScrolled(int xpos) {
1142        final int widthWithMargin = getWidth() + mPageMargin;
1143        final int position = xpos / widthWithMargin;
1144        final int offsetPixels = xpos % widthWithMargin;
1145        final float offset = (float) offsetPixels / widthWithMargin;
1146
1147        mCalledSuper = false;
1148        onPageScrolled(position, offset, offsetPixels);
1149        if (!mCalledSuper) {
1150            throw new IllegalStateException(
1151                    "onPageScrolled did not call superclass implementation");
1152        }
1153    }
1154
1155    /**
1156     * This method will be invoked when the current page is scrolled, either as part
1157     * of a programmatically initiated smooth scroll or a user initiated touch scroll.
1158     * If you override this method you must call through to the superclass implementation
1159     * (e.g. super.onPageScrolled(position, offset, offsetPixels)) before onPageScrolled
1160     * returns.
1161     *
1162     * @param position Position index of the first page currently being displayed.
1163     *                 Page position+1 will be visible if positionOffset is nonzero.
1164     * @param offset Value from [0, 1) indicating the offset from the page at position.
1165     * @param offsetPixels Value in pixels indicating the offset from position.
1166     */
1167    protected void onPageScrolled(int position, float offset, int offsetPixels) {
1168        // Offset any decor views if needed - keep them on-screen at all times.
1169        if (mDecorChildCount > 0) {
1170            final int scrollX = getScrollX();
1171            int paddingLeft = getPaddingLeft();
1172            int paddingRight = getPaddingRight();
1173            final int width = getWidth();
1174            final int childCount = getChildCount();
1175            for (int i = 0; i < childCount; i++) {
1176                final View child = getChildAt(i);
1177                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
1178                if (!lp.isDecor) continue;
1179
1180                final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
1181                int childLeft = 0;
1182                switch (hgrav) {
1183                    default:
1184                        childLeft = paddingLeft;
1185                        break;
1186                    case Gravity.LEFT:
1187                        childLeft = paddingLeft;
1188                        paddingLeft += child.getWidth();
1189                        break;
1190                    case Gravity.CENTER_HORIZONTAL:
1191                        childLeft = Math.max((width - child.getMeasuredWidth()) / 2,
1192                                paddingLeft);
1193                        break;
1194                    case Gravity.RIGHT:
1195                        childLeft = width - paddingRight - child.getMeasuredWidth();
1196                        paddingRight += child.getMeasuredWidth();
1197                        break;
1198                }
1199                childLeft += scrollX;
1200
1201                final int childOffset = childLeft - child.getLeft();
1202                if (childOffset != 0) {
1203                    child.offsetLeftAndRight(childOffset);
1204                }
1205            }
1206        }
1207
1208        if (mOnPageChangeListener != null) {
1209            mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels);
1210        }
1211        if (mInternalPageChangeListener != null) {
1212            mInternalPageChangeListener.onPageScrolled(position, offset, offsetPixels);
1213        }
1214        mCalledSuper = true;
1215    }
1216
1217    private void completeScroll() {
1218        boolean needPopulate = mScrolling;
1219        if (needPopulate) {
1220            // Done with scroll, no longer want to cache view drawing.
1221            setScrollingCacheEnabled(false);
1222            mScroller.abortAnimation();
1223            int oldX = getScrollX();
1224            int oldY = getScrollY();
1225            int x = mScroller.getCurrX();
1226            int y = mScroller.getCurrY();
1227            if (oldX != x || oldY != y) {
1228                scrollTo(x, y);
1229            }
1230            setScrollState(SCROLL_STATE_IDLE);
1231        }
1232        mPopulatePending = false;
1233        mScrolling = false;
1234        for (int i=0; i<mItems.size(); i++) {
1235            ItemInfo ii = mItems.get(i);
1236            if (ii.scrolling) {
1237                needPopulate = true;
1238                ii.scrolling = false;
1239            }
1240        }
1241        if (needPopulate) {
1242            populate();
1243        }
1244    }
1245
1246    @Override
1247    public boolean onInterceptTouchEvent(MotionEvent ev) {
1248        /*
1249         * This method JUST determines whether we want to intercept the motion.
1250         * If we return true, onMotionEvent will be called and we do the actual
1251         * scrolling there.
1252         */
1253
1254        final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
1255
1256        // Always take care of the touch gesture being complete.
1257        if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
1258            // Release the drag.
1259            if (DEBUG) Log.v(TAG, "Intercept done!");
1260            mIsBeingDragged = false;
1261            mIsUnableToDrag = false;
1262            mActivePointerId = INVALID_POINTER;
1263            if (mVelocityTracker != null) {
1264                mVelocityTracker.recycle();
1265                mVelocityTracker = null;
1266            }
1267            return false;
1268        }
1269
1270        // Nothing more to do here if we have decided whether or not we
1271        // are dragging.
1272        if (action != MotionEvent.ACTION_DOWN) {
1273            if (mIsBeingDragged) {
1274                if (DEBUG) Log.v(TAG, "Intercept returning true!");
1275                return true;
1276            }
1277            if (mIsUnableToDrag) {
1278                if (DEBUG) Log.v(TAG, "Intercept returning false!");
1279                return false;
1280            }
1281        }
1282
1283        switch (action) {
1284            case MotionEvent.ACTION_MOVE: {
1285                /*
1286                 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1287                 * whether the user has moved far enough from his original down touch.
1288                 */
1289
1290                /*
1291                * Locally do absolute value. mLastMotionY is set to the y value
1292                * of the down event.
1293                */
1294                final int activePointerId = mActivePointerId;
1295                if (activePointerId == INVALID_POINTER) {
1296                    // If we don't have a valid id, the touch down wasn't on content.
1297                    break;
1298                }
1299
1300                final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId);
1301                final float x = MotionEventCompat.getX(ev, pointerIndex);
1302                final float dx = x - mLastMotionX;
1303                final float xDiff = Math.abs(dx);
1304                final float y = MotionEventCompat.getY(ev, pointerIndex);
1305                final float yDiff = Math.abs(y - mLastMotionY);
1306                final int scrollX = getScrollX();
1307                if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff);
1308
1309                if (canScroll(this, false, (int) dx, (int) x, (int) y)) {
1310                    // Nested view has scrollable area under this point. Let it be handled there.
1311                    mInitialMotionX = mLastMotionX = x;
1312                    mLastMotionY = y;
1313                    return false;
1314                }
1315                if (xDiff > mTouchSlop && xDiff > yDiff) {
1316                    if (DEBUG) Log.v(TAG, "Starting drag!");
1317                    mIsBeingDragged = true;
1318                    setScrollState(SCROLL_STATE_DRAGGING);
1319                    mLastMotionX = x;
1320                    setScrollingCacheEnabled(true);
1321                } else {
1322                    if (yDiff > mTouchSlop) {
1323                        // The finger has moved enough in the vertical
1324                        // direction to be counted as a drag...  abort
1325                        // any attempt to drag horizontally, to work correctly
1326                        // with children that have scrolling containers.
1327                        if (DEBUG) Log.v(TAG, "Starting unable to drag!");
1328                        mIsUnableToDrag = true;
1329                    }
1330                }
1331                break;
1332            }
1333
1334            case MotionEvent.ACTION_DOWN: {
1335                /*
1336                 * Remember location of down touch.
1337                 * ACTION_DOWN always refers to pointer index 0.
1338                 */
1339                mLastMotionX = mInitialMotionX = ev.getX();
1340                mLastMotionY = ev.getY();
1341                mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
1342
1343                if (mScrollState == SCROLL_STATE_SETTLING) {
1344                    // Let the user 'catch' the pager as it animates.
1345                    mIsBeingDragged = true;
1346                    mIsUnableToDrag = false;
1347                    setScrollState(SCROLL_STATE_DRAGGING);
1348                } else {
1349                    completeScroll();
1350                    mIsBeingDragged = false;
1351                    mIsUnableToDrag = false;
1352                }
1353
1354                if (DEBUG) Log.v(TAG, "Down at " + mLastMotionX + "," + mLastMotionY
1355                        + " mIsBeingDragged=" + mIsBeingDragged
1356                        + "mIsUnableToDrag=" + mIsUnableToDrag);
1357                break;
1358            }
1359
1360            case MotionEventCompat.ACTION_POINTER_UP:
1361                onSecondaryPointerUp(ev);
1362                break;
1363        }
1364
1365        if (!mIsBeingDragged) {
1366            // Track the velocity as long as we aren't dragging.
1367            // Once we start a real drag we will track in onTouchEvent.
1368            if (mVelocityTracker == null) {
1369                mVelocityTracker = VelocityTracker.obtain();
1370            }
1371            mVelocityTracker.addMovement(ev);
1372        }
1373
1374        /*
1375         * The only time we want to intercept motion events is if we are in the
1376         * drag mode.
1377         */
1378        return mIsBeingDragged;
1379    }
1380
1381    @Override
1382    public boolean onTouchEvent(MotionEvent ev) {
1383        if (mFakeDragging) {
1384            // A fake drag is in progress already, ignore this real one
1385            // but still eat the touch events.
1386            // (It is likely that the user is multi-touching the screen.)
1387            return true;
1388        }
1389
1390        if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
1391            // Don't handle edge touches immediately -- they may actually belong to one of our
1392            // descendants.
1393            return false;
1394        }
1395
1396        if (mAdapter == null || mAdapter.getCount() == 0) {
1397            // Nothing to present or scroll; nothing to touch.
1398            return false;
1399        }
1400
1401        if (mVelocityTracker == null) {
1402            mVelocityTracker = VelocityTracker.obtain();
1403        }
1404        mVelocityTracker.addMovement(ev);
1405
1406        final int action = ev.getAction();
1407        boolean needsInvalidate = false;
1408
1409        switch (action & MotionEventCompat.ACTION_MASK) {
1410            case MotionEvent.ACTION_DOWN: {
1411                /*
1412                 * If being flinged and user touches, stop the fling. isFinished
1413                 * will be false if being flinged.
1414                 */
1415                completeScroll();
1416
1417                // Remember where the motion event started
1418                mLastMotionX = mInitialMotionX = ev.getX();
1419                mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
1420                break;
1421            }
1422            case MotionEvent.ACTION_MOVE:
1423                if (!mIsBeingDragged) {
1424                    final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
1425                    final float x = MotionEventCompat.getX(ev, pointerIndex);
1426                    final float xDiff = Math.abs(x - mLastMotionX);
1427                    final float y = MotionEventCompat.getY(ev, pointerIndex);
1428                    final float yDiff = Math.abs(y - mLastMotionY);
1429                    if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff);
1430                    if (xDiff > mTouchSlop && xDiff > yDiff) {
1431                        if (DEBUG) Log.v(TAG, "Starting drag!");
1432                        mIsBeingDragged = true;
1433                        mLastMotionX = x;
1434                        setScrollState(SCROLL_STATE_DRAGGING);
1435                        setScrollingCacheEnabled(true);
1436                    }
1437                }
1438                if (mIsBeingDragged) {
1439                    // Scroll to follow the motion event
1440                    final int activePointerIndex = MotionEventCompat.findPointerIndex(
1441                            ev, mActivePointerId);
1442                    final float x = MotionEventCompat.getX(ev, activePointerIndex);
1443                    final float deltaX = mLastMotionX - x;
1444                    mLastMotionX = x;
1445                    float oldScrollX = getScrollX();
1446                    float scrollX = oldScrollX + deltaX;
1447                    final int width = getWidth();
1448                    final int widthWithMargin = width + mPageMargin;
1449
1450                    final int lastItemIndex = mAdapter.getCount() - 1;
1451                    final float leftBound = Math.max(0, (mCurItem - 1) * widthWithMargin);
1452                    final float rightBound =
1453                            Math.min(mCurItem + 1, lastItemIndex) * widthWithMargin;
1454                    if (scrollX < leftBound) {
1455                        if (leftBound == 0) {
1456                            float over = -scrollX;
1457                            needsInvalidate = mLeftEdge.onPull(over / width);
1458                        }
1459                        scrollX = leftBound;
1460                    } else if (scrollX > rightBound) {
1461                        if (rightBound == lastItemIndex * widthWithMargin) {
1462                            float over = scrollX - rightBound;
1463                            needsInvalidate = mRightEdge.onPull(over / width);
1464                        }
1465                        scrollX = rightBound;
1466                    }
1467                    // Don't lose the rounded component
1468                    mLastMotionX += scrollX - (int) scrollX;
1469                    scrollTo((int) scrollX, getScrollY());
1470                    pageScrolled((int) scrollX);
1471                }
1472                break;
1473            case MotionEvent.ACTION_UP:
1474                if (mIsBeingDragged) {
1475                    final VelocityTracker velocityTracker = mVelocityTracker;
1476                    velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1477                    int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(
1478                            velocityTracker, mActivePointerId);
1479                    mPopulatePending = true;
1480                    final int widthWithMargin = getWidth() + mPageMargin;
1481                    final int scrollX = getScrollX();
1482                    final int currentPage = scrollX / widthWithMargin;
1483                    int nextPage = initialVelocity > 0 ? currentPage : currentPage + 1;
1484                    setCurrentItemInternal(nextPage, true, true, initialVelocity);
1485
1486                    mActivePointerId = INVALID_POINTER;
1487                    endDrag();
1488                    needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();
1489                }
1490                break;
1491            case MotionEvent.ACTION_CANCEL:
1492                if (mIsBeingDragged) {
1493                    setCurrentItemInternal(mCurItem, true, true);
1494                    mActivePointerId = INVALID_POINTER;
1495                    endDrag();
1496                    needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();
1497                }
1498                break;
1499            case MotionEventCompat.ACTION_POINTER_DOWN: {
1500                final int index = MotionEventCompat.getActionIndex(ev);
1501                final float x = MotionEventCompat.getX(ev, index);
1502                mLastMotionX = x;
1503                mActivePointerId = MotionEventCompat.getPointerId(ev, index);
1504                break;
1505            }
1506            case MotionEventCompat.ACTION_POINTER_UP:
1507                onSecondaryPointerUp(ev);
1508                mLastMotionX = MotionEventCompat.getX(ev,
1509                        MotionEventCompat.findPointerIndex(ev, mActivePointerId));
1510                break;
1511        }
1512        if (needsInvalidate) {
1513            invalidate();
1514        }
1515        return true;
1516    }
1517
1518    @Override
1519    public void draw(Canvas canvas) {
1520        super.draw(canvas);
1521        boolean needsInvalidate = false;
1522
1523        final int overScrollMode = ViewCompat.getOverScrollMode(this);
1524        if (overScrollMode == ViewCompat.OVER_SCROLL_ALWAYS ||
1525                (overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS &&
1526                        mAdapter != null && mAdapter.getCount() > 1)) {
1527            if (!mLeftEdge.isFinished()) {
1528                final int restoreCount = canvas.save();
1529                final int height = getHeight() - getPaddingTop() - getPaddingBottom();
1530
1531                canvas.rotate(270);
1532                canvas.translate(-height + getPaddingTop(), 0);
1533                mLeftEdge.setSize(height, getWidth());
1534                needsInvalidate |= mLeftEdge.draw(canvas);
1535                canvas.restoreToCount(restoreCount);
1536            }
1537            if (!mRightEdge.isFinished()) {
1538                final int restoreCount = canvas.save();
1539                final int width = getWidth();
1540                final int height = getHeight() - getPaddingTop() - getPaddingBottom();
1541                final int itemCount = mAdapter != null ? mAdapter.getCount() : 1;
1542
1543                canvas.rotate(90);
1544                canvas.translate(-getPaddingTop(),
1545                        -itemCount * (width + mPageMargin) + mPageMargin);
1546                mRightEdge.setSize(height, width);
1547                needsInvalidate |= mRightEdge.draw(canvas);
1548                canvas.restoreToCount(restoreCount);
1549            }
1550        } else {
1551            mLeftEdge.finish();
1552            mRightEdge.finish();
1553        }
1554
1555        if (needsInvalidate) {
1556            // Keep animating
1557            invalidate();
1558        }
1559    }
1560
1561    @Override
1562    protected void onDraw(Canvas canvas) {
1563        super.onDraw(canvas);
1564
1565        // Draw the margin drawable if needed.
1566        if (mPageMargin > 0 && mMarginDrawable != null) {
1567            final int scrollX = getScrollX();
1568            final int width = getWidth();
1569            final int offset = scrollX % (width + mPageMargin);
1570            if (offset != 0) {
1571                // Pages fit completely when settled; we only need to draw when in between
1572                final int left = scrollX - offset + width;
1573                mMarginDrawable.setBounds(left, mTopPageBounds, left + mPageMargin,
1574                        mBottomPageBounds);
1575                mMarginDrawable.draw(canvas);
1576            }
1577        }
1578    }
1579
1580    /**
1581     * Start a fake drag of the pager.
1582     *
1583     * <p>A fake drag can be useful if you want to synchronize the motion of the ViewPager
1584     * with the touch scrolling of another view, while still letting the ViewPager
1585     * control the snapping motion and fling behavior. (e.g. parallax-scrolling tabs.)
1586     * Call {@link #fakeDragBy(float)} to simulate the actual drag motion. Call
1587     * {@link #endFakeDrag()} to complete the fake drag and fling as necessary.
1588     *
1589     * <p>During a fake drag the ViewPager will ignore all touch events. If a real drag
1590     * is already in progress, this method will return false.
1591     *
1592     * @return true if the fake drag began successfully, false if it could not be started.
1593     *
1594     * @see #fakeDragBy(float)
1595     * @see #endFakeDrag()
1596     */
1597    public boolean beginFakeDrag() {
1598        if (mIsBeingDragged) {
1599            return false;
1600        }
1601        mFakeDragging = true;
1602        setScrollState(SCROLL_STATE_DRAGGING);
1603        mInitialMotionX = mLastMotionX = 0;
1604        if (mVelocityTracker == null) {
1605            mVelocityTracker = VelocityTracker.obtain();
1606        } else {
1607            mVelocityTracker.clear();
1608        }
1609        final long time = SystemClock.uptimeMillis();
1610        final MotionEvent ev = MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, 0, 0, 0);
1611        mVelocityTracker.addMovement(ev);
1612        ev.recycle();
1613        mFakeDragBeginTime = time;
1614        return true;
1615    }
1616
1617    /**
1618     * End a fake drag of the pager.
1619     *
1620     * @see #beginFakeDrag()
1621     * @see #fakeDragBy(float)
1622     */
1623    public void endFakeDrag() {
1624        if (!mFakeDragging) {
1625            throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first.");
1626        }
1627
1628        final VelocityTracker velocityTracker = mVelocityTracker;
1629        velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1630        int initialVelocity = (int)VelocityTrackerCompat.getYVelocity(
1631                velocityTracker, mActivePointerId);
1632        mPopulatePending = true;
1633        if ((Math.abs(initialVelocity) > mMinimumVelocity)
1634                || Math.abs(mInitialMotionX-mLastMotionX) >= (getWidth()/3)) {
1635            if (mLastMotionX > mInitialMotionX) {
1636                setCurrentItemInternal(mCurItem-1, true, true);
1637            } else {
1638                setCurrentItemInternal(mCurItem+1, true, true);
1639            }
1640        } else {
1641            setCurrentItemInternal(mCurItem, true, true);
1642        }
1643        endDrag();
1644
1645        mFakeDragging = false;
1646    }
1647
1648    /**
1649     * Fake drag by an offset in pixels. You must have called {@link #beginFakeDrag()} first.
1650     *
1651     * @param xOffset Offset in pixels to drag by.
1652     * @see #beginFakeDrag()
1653     * @see #endFakeDrag()
1654     */
1655    public void fakeDragBy(float xOffset) {
1656        if (!mFakeDragging) {
1657            throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first.");
1658        }
1659
1660        mLastMotionX += xOffset;
1661        float scrollX = getScrollX() - xOffset;
1662        final int width = getWidth();
1663        final int widthWithMargin = width + mPageMargin;
1664
1665        final float leftBound = Math.max(0, (mCurItem - 1) * widthWithMargin);
1666        final float rightBound =
1667                Math.min(mCurItem + 1, mAdapter.getCount() - 1) * widthWithMargin;
1668        if (scrollX < leftBound) {
1669            scrollX = leftBound;
1670        } else if (scrollX > rightBound) {
1671            scrollX = rightBound;
1672        }
1673        // Don't lose the rounded component
1674        mLastMotionX += scrollX - (int) scrollX;
1675        scrollTo((int) scrollX, getScrollY());
1676        pageScrolled((int) scrollX);
1677
1678        // Synthesize an event for the VelocityTracker.
1679        final long time = SystemClock.uptimeMillis();
1680        final MotionEvent ev = MotionEvent.obtain(mFakeDragBeginTime, time, MotionEvent.ACTION_MOVE,
1681                mLastMotionX, 0, 0);
1682        mVelocityTracker.addMovement(ev);
1683        ev.recycle();
1684    }
1685
1686    /**
1687     * Returns true if a fake drag is in progress.
1688     *
1689     * @return true if currently in a fake drag, false otherwise.
1690     *
1691     * @see #beginFakeDrag()
1692     * @see #fakeDragBy(float)
1693     * @see #endFakeDrag()
1694     */
1695    public boolean isFakeDragging() {
1696        return mFakeDragging;
1697    }
1698
1699    private void onSecondaryPointerUp(MotionEvent ev) {
1700        final int pointerIndex = MotionEventCompat.getActionIndex(ev);
1701        final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
1702        if (pointerId == mActivePointerId) {
1703            // This was our active pointer going up. Choose a new
1704            // active pointer and adjust accordingly.
1705            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1706            mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex);
1707            mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
1708            if (mVelocityTracker != null) {
1709                mVelocityTracker.clear();
1710            }
1711        }
1712    }
1713
1714    private void endDrag() {
1715        mIsBeingDragged = false;
1716        mIsUnableToDrag = false;
1717
1718        if (mVelocityTracker != null) {
1719            mVelocityTracker.recycle();
1720            mVelocityTracker = null;
1721        }
1722    }
1723
1724    private void setScrollingCacheEnabled(boolean enabled) {
1725        if (mScrollingCacheEnabled != enabled) {
1726            mScrollingCacheEnabled = enabled;
1727            if (USE_CACHE) {
1728                final int size = getChildCount();
1729                for (int i = 0; i < size; ++i) {
1730                    final View child = getChildAt(i);
1731                    if (child.getVisibility() != GONE) {
1732                        child.setDrawingCacheEnabled(enabled);
1733                    }
1734                }
1735            }
1736        }
1737    }
1738
1739    /**
1740     * Tests scrollability within child views of v given a delta of dx.
1741     *
1742     * @param v View to test for horizontal scrollability
1743     * @param checkV Whether the view v passed should itself be checked for scrollability (true),
1744     *               or just its children (false).
1745     * @param dx Delta scrolled in pixels
1746     * @param x X coordinate of the active touch point
1747     * @param y Y coordinate of the active touch point
1748     * @return true if child views of v can be scrolled by delta of dx.
1749     */
1750    protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
1751        if (v instanceof ViewGroup) {
1752            final ViewGroup group = (ViewGroup) v;
1753            final int scrollX = v.getScrollX();
1754            final int scrollY = v.getScrollY();
1755            final int count = group.getChildCount();
1756            // Count backwards - let topmost views consume scroll distance first.
1757            for (int i = count - 1; i >= 0; i--) {
1758                // TODO: Add versioned support here for transformed views.
1759                // This will not work for transformed views in Honeycomb+
1760                final View child = group.getChildAt(i);
1761                if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() &&
1762                        y + scrollY >= child.getTop() && y + scrollY < child.getBottom() &&
1763                        canScroll(child, true, dx, x + scrollX - child.getLeft(),
1764                                y + scrollY - child.getTop())) {
1765                    return true;
1766                }
1767            }
1768        }
1769
1770        return checkV && ViewCompat.canScrollHorizontally(v, -dx);
1771    }
1772
1773    @Override
1774    public boolean dispatchKeyEvent(KeyEvent event) {
1775        // Let the focused view and/or our descendants get the key first
1776        return super.dispatchKeyEvent(event) || executeKeyEvent(event);
1777    }
1778
1779    /**
1780     * You can call this function yourself to have the scroll view perform
1781     * scrolling from a key event, just as if the event had been dispatched to
1782     * it by the view hierarchy.
1783     *
1784     * @param event The key event to execute.
1785     * @return Return true if the event was handled, else false.
1786     */
1787    public boolean executeKeyEvent(KeyEvent event) {
1788        boolean handled = false;
1789        if (event.getAction() == KeyEvent.ACTION_DOWN) {
1790            switch (event.getKeyCode()) {
1791                case KeyEvent.KEYCODE_DPAD_LEFT:
1792                    handled = arrowScroll(FOCUS_LEFT);
1793                    break;
1794                case KeyEvent.KEYCODE_DPAD_RIGHT:
1795                    handled = arrowScroll(FOCUS_RIGHT);
1796                    break;
1797                case KeyEvent.KEYCODE_TAB:
1798                    if (KeyEventCompat.hasNoModifiers(event)) {
1799                        handled = arrowScroll(FOCUS_FORWARD);
1800                    } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) {
1801                        handled = arrowScroll(FOCUS_BACKWARD);
1802                    }
1803                    break;
1804            }
1805        }
1806        return handled;
1807    }
1808
1809    public boolean arrowScroll(int direction) {
1810        View currentFocused = findFocus();
1811        if (currentFocused == this) currentFocused = null;
1812
1813        boolean handled = false;
1814
1815        View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused,
1816                direction);
1817        if (nextFocused != null && nextFocused != currentFocused) {
1818            if (direction == View.FOCUS_LEFT) {
1819                // If there is nothing to the left, or this is causing us to
1820                // jump to the right, then what we really want to do is page left.
1821                if (currentFocused != null && nextFocused.getLeft() >= currentFocused.getLeft()) {
1822                    handled = pageLeft();
1823                } else {
1824                    handled = nextFocused.requestFocus();
1825                }
1826            } else if (direction == View.FOCUS_RIGHT) {
1827                // If there is nothing to the right, or this is causing us to
1828                // jump to the left, then what we really want to do is page right.
1829                if (currentFocused != null && nextFocused.getLeft() <= currentFocused.getLeft()) {
1830                    handled = pageRight();
1831                } else {
1832                    handled = nextFocused.requestFocus();
1833                }
1834            }
1835        } else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) {
1836            // Trying to move left and nothing there; try to page.
1837            handled = pageLeft();
1838        } else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) {
1839            // Trying to move right and nothing there; try to page.
1840            handled = pageRight();
1841        }
1842        if (handled) {
1843            playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
1844        }
1845        return handled;
1846    }
1847
1848    boolean pageLeft() {
1849        if (mCurItem > 0) {
1850            setCurrentItem(mCurItem-1, true);
1851            return true;
1852        }
1853        return false;
1854    }
1855
1856    boolean pageRight() {
1857        if (mAdapter != null && mCurItem < (mAdapter.getCount()-1)) {
1858            setCurrentItem(mCurItem+1, true);
1859            return true;
1860        }
1861        return false;
1862    }
1863
1864    /**
1865     * We only want the current page that is being shown to be focusable.
1866     */
1867    @Override
1868    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
1869        final int focusableCount = views.size();
1870
1871        final int descendantFocusability = getDescendantFocusability();
1872
1873        if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
1874            for (int i = 0; i < getChildCount(); i++) {
1875                final View child = getChildAt(i);
1876                if (child.getVisibility() == VISIBLE) {
1877                    ItemInfo ii = infoForChild(child);
1878                    if (ii != null && ii.position == mCurItem) {
1879                        child.addFocusables(views, direction, focusableMode);
1880                    }
1881                }
1882            }
1883        }
1884
1885        // we add ourselves (if focusable) in all cases except for when we are
1886        // FOCUS_AFTER_DESCENDANTS and there are some descendants focusable.  this is
1887        // to avoid the focus search finding layouts when a more precise search
1888        // among the focusable children would be more interesting.
1889        if (
1890            descendantFocusability != FOCUS_AFTER_DESCENDANTS ||
1891                // No focusable descendants
1892                (focusableCount == views.size())) {
1893            // Note that we can't call the superclass here, because it will
1894            // add all views in.  So we need to do the same thing View does.
1895            if (!isFocusable()) {
1896                return;
1897            }
1898            if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
1899                    isInTouchMode() && !isFocusableInTouchMode()) {
1900                return;
1901            }
1902            if (views != null) {
1903                views.add(this);
1904            }
1905        }
1906    }
1907
1908    /**
1909     * We only want the current page that is being shown to be touchable.
1910     */
1911    @Override
1912    public void addTouchables(ArrayList<View> views) {
1913        // Note that we don't call super.addTouchables(), which means that
1914        // we don't call View.addTouchables().  This is okay because a ViewPager
1915        // is itself not touchable.
1916        for (int i = 0; i < getChildCount(); i++) {
1917            final View child = getChildAt(i);
1918            if (child.getVisibility() == VISIBLE) {
1919                ItemInfo ii = infoForChild(child);
1920                if (ii != null && ii.position == mCurItem) {
1921                    child.addTouchables(views);
1922                }
1923            }
1924        }
1925    }
1926
1927    /**
1928     * We only want the current page that is being shown to be focusable.
1929     */
1930    @Override
1931    protected boolean onRequestFocusInDescendants(int direction,
1932            Rect previouslyFocusedRect) {
1933        int index;
1934        int increment;
1935        int end;
1936        int count = getChildCount();
1937        if ((direction & FOCUS_FORWARD) != 0) {
1938            index = 0;
1939            increment = 1;
1940            end = count;
1941        } else {
1942            index = count - 1;
1943            increment = -1;
1944            end = -1;
1945        }
1946        for (int i = index; i != end; i += increment) {
1947            View child = getChildAt(i);
1948            if (child.getVisibility() == VISIBLE) {
1949                ItemInfo ii = infoForChild(child);
1950                if (ii != null && ii.position == mCurItem) {
1951                    if (child.requestFocus(direction, previouslyFocusedRect)) {
1952                        return true;
1953                    }
1954                }
1955            }
1956        }
1957        return false;
1958    }
1959
1960    @Override
1961    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
1962        // ViewPagers should only report accessibility info for the current page,
1963        // otherwise things get very confusing.
1964
1965        // TODO: Should this note something about the paging container?
1966
1967        final int childCount = getChildCount();
1968        for (int i = 0; i < childCount; i++) {
1969            final View child = getChildAt(i);
1970            if (child.getVisibility() == VISIBLE) {
1971                final ItemInfo ii = infoForChild(child);
1972                if (ii != null && ii.position == mCurItem &&
1973                        child.dispatchPopulateAccessibilityEvent(event)) {
1974                    return true;
1975                }
1976            }
1977        }
1978
1979        return false;
1980    }
1981
1982    @Override
1983    protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
1984        return new LayoutParams();
1985    }
1986
1987    @Override
1988    protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
1989        return generateDefaultLayoutParams();
1990    }
1991
1992    @Override
1993    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
1994        return p instanceof LayoutParams && super.checkLayoutParams(p);
1995    }
1996
1997    @Override
1998    public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
1999        return new LayoutParams(getContext(), attrs);
2000    }
2001
2002    private class PagerObserver extends DataSetObserver {
2003        @Override
2004        public void onChanged() {
2005            dataSetChanged();
2006        }
2007        @Override
2008        public void onInvalidated() {
2009            dataSetChanged();
2010        }
2011    }
2012
2013    public static class LayoutParams extends ViewGroup.LayoutParams {
2014        /**
2015         * true if this view is a decoration on the pager itself and not
2016         * a view supplied by the adapter.
2017         */
2018        public boolean isDecor;
2019
2020        public int gravity;
2021
2022        public LayoutParams() {
2023            super(FILL_PARENT, FILL_PARENT);
2024        }
2025
2026        public LayoutParams(Context context, AttributeSet attrs) {
2027            super(context, attrs);
2028
2029            final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
2030            gravity = a.getInteger(0, Gravity.NO_GRAVITY);
2031            a.recycle();
2032        }
2033    }
2034}
2035