GridLayoutManager.java revision b33714d135e006cf3bdba09788c27d4791b8632e
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License
10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 * or implied. See the License for the specific language governing permissions and limitations under
12 * the License.
13 */
14package android.support.v17.leanback.widget;
15
16import android.content.Context;
17import android.graphics.PointF;
18import android.graphics.Rect;
19import android.os.Bundle;
20import android.os.Parcel;
21import android.os.Parcelable;
22import android.support.v4.view.ViewCompat;
23import android.support.v7.widget.LinearSmoothScroller;
24import android.support.v7.widget.RecyclerView;
25import android.support.v7.widget.RecyclerView.Recycler;
26import android.support.v7.widget.RecyclerView.State;
27
28import static android.support.v7.widget.RecyclerView.NO_ID;
29import static android.support.v7.widget.RecyclerView.NO_POSITION;
30import static android.support.v7.widget.RecyclerView.HORIZONTAL;
31import static android.support.v7.widget.RecyclerView.VERTICAL;
32
33import android.util.AttributeSet;
34import android.util.Log;
35import android.view.FocusFinder;
36import android.view.Gravity;
37import android.view.View;
38import android.view.ViewParent;
39import android.view.View.MeasureSpec;
40import android.view.ViewGroup.MarginLayoutParams;
41import android.view.ViewGroup;
42
43import java.io.PrintWriter;
44import java.io.StringWriter;
45import java.util.ArrayList;
46import java.util.List;
47
48final class GridLayoutManager extends RecyclerView.LayoutManager {
49
50     /*
51      * LayoutParams for {@link HorizontalGridView} and {@link VerticalGridView}.
52      * The class currently does two internal jobs:
53      * - Saves optical bounds insets.
54      * - Caches focus align view center.
55      */
56    static class LayoutParams extends RecyclerView.LayoutParams {
57
58        // The view is saved only during animation.
59        private View mView;
60
61        // For placement
62        private int mLeftInset;
63        private int mTopInset;
64        private int mRighInset;
65        private int mBottomInset;
66
67        // For alignment
68        private int mAlignX;
69        private int mAlignY;
70
71        public LayoutParams(Context c, AttributeSet attrs) {
72            super(c, attrs);
73        }
74
75        public LayoutParams(int width, int height) {
76            super(width, height);
77        }
78
79        public LayoutParams(MarginLayoutParams source) {
80            super(source);
81        }
82
83        public LayoutParams(ViewGroup.LayoutParams source) {
84            super(source);
85        }
86
87        public LayoutParams(RecyclerView.LayoutParams source) {
88            super(source);
89        }
90
91        public LayoutParams(LayoutParams source) {
92            super(source);
93        }
94
95        int getAlignX() {
96            return mAlignX;
97        }
98
99        int getAlignY() {
100            return mAlignY;
101        }
102
103        int getOpticalLeft(View view) {
104            return view.getLeft() + mLeftInset;
105        }
106
107        int getOpticalTop(View view) {
108            return view.getTop() + mTopInset;
109        }
110
111        int getOpticalRight(View view) {
112            return view.getRight() - mRighInset;
113        }
114
115        int getOpticalBottom(View view) {
116            return view.getBottom() - mBottomInset;
117        }
118
119        int getOpticalWidth(View view) {
120            return view.getWidth() - mLeftInset - mRighInset;
121        }
122
123        int getOpticalHeight(View view) {
124            return view.getHeight() - mTopInset - mBottomInset;
125        }
126
127        int getOpticalLeftInset() {
128            return mLeftInset;
129        }
130
131        int getOpticalRightInset() {
132            return mRighInset;
133        }
134
135        int getOpticalTopInset() {
136            return mTopInset;
137        }
138
139        int getOpticalBottomInset() {
140            return mBottomInset;
141        }
142
143        void setAlignX(int alignX) {
144            mAlignX = alignX;
145        }
146
147        void setAlignY(int alignY) {
148            mAlignY = alignY;
149        }
150
151        void setOpticalInsets(int leftInset, int topInset, int rightInset, int bottomInset) {
152            mLeftInset = leftInset;
153            mTopInset = topInset;
154            mRighInset = rightInset;
155            mBottomInset = bottomInset;
156        }
157
158        private void invalidateItemDecoration() {
159            ViewParent parent = mView.getParent();
160            if (parent instanceof RecyclerView) {
161                // TODO: we only need invalidate parent if it has ItemDecoration
162                ((RecyclerView) parent).invalidate();
163            }
164        }
165    }
166
167    private static final String TAG = "GridLayoutManager";
168    private static final boolean DEBUG = false;
169
170    private String getTag() {
171        return TAG + ":" + mBaseGridView.getId();
172    }
173
174    private final BaseGridView mBaseGridView;
175
176    /**
177     * The orientation of a "row".
178     */
179    private int mOrientation = HORIZONTAL;
180
181    private RecyclerView.State mState;
182    private RecyclerView.Recycler mRecycler;
183
184    private boolean mInLayout = false;
185    private boolean mInSelection = false;
186
187    private OnChildSelectedListener mChildSelectedListener = null;
188
189    /**
190     * The focused position, it's not the currently visually aligned position
191     * but it is the final position that we intend to focus on. If there are
192     * multiple setSelection() called, mFocusPosition saves last value.
193     */
194    private int mFocusPosition = NO_POSITION;
195
196    /**
197     * The offset to be applied to mFocusPosition, due to adapter change, on the next
198     * layout.  Set to Integer.MIN_VALUE means item was removed.
199     * TODO:  This is somewhat duplication of RecyclerView getOldPosition() which is
200     * unfortunately cleared after prelayout.
201     */
202    private int mFocusPositionOffset = 0;
203
204    /**
205     * Force a full layout under certain situations.
206     */
207    private boolean mForceFullLayout;
208
209    /**
210     * True if layout is enabled.
211     */
212    private boolean mLayoutEnabled = true;
213
214    /**
215     * The scroll offsets of the viewport relative to the entire view.
216     */
217    private int mScrollOffsetPrimary;
218    private int mScrollOffsetSecondary;
219
220    /**
221     * User-specified row height/column width.  Can be WRAP_CONTENT.
222     */
223    private int mRowSizeSecondaryRequested;
224
225    /**
226     * The fixed size of each grid item in the secondary direction. This corresponds to
227     * the row height, equal for all rows. Grid items may have variable length
228     * in the primary direction.
229     */
230    private int mFixedRowSizeSecondary;
231
232    /**
233     * Tracks the secondary size of each row.
234     */
235    private int[] mRowSizeSecondary;
236
237    /**
238     * Flag controlling whether the current/next layout should
239     * be updating the secondary size of rows.
240     */
241    private boolean mRowSecondarySizeRefresh;
242
243    /**
244     * The maximum measured size of the view.
245     */
246    private int mMaxSizeSecondary;
247
248    /**
249     * Margin between items.
250     */
251    private int mHorizontalMargin;
252    /**
253     * Margin between items vertically.
254     */
255    private int mVerticalMargin;
256    /**
257     * Margin in main direction.
258     */
259    private int mMarginPrimary;
260    /**
261     * Margin in second direction.
262     */
263    private int mMarginSecondary;
264    /**
265     * How to position child in secondary direction.
266     */
267    private int mGravity = Gravity.LEFT | Gravity.TOP;
268    /**
269     * The number of rows in the grid.
270     */
271    private int mNumRows;
272    /**
273     * Number of rows requested, can be 0 to be determined by parent size and
274     * rowHeight.
275     */
276    private int mNumRowsRequested = 1;
277
278    /**
279     * Tracking start/end position of each row for visible items.
280     */
281    private StaggeredGrid.Row[] mRows;
282
283    /**
284     * Saves grid information of each view.
285     */
286    private StaggeredGrid mGrid;
287    /**
288     * Position of first item (included) that has attached views.
289     */
290    private int mFirstVisiblePos;
291    /**
292     * Position of last item (included) that has attached views.
293     */
294    private int mLastVisiblePos;
295
296    /**
297     * Focus Scroll strategy.
298     */
299    private int mFocusScrollStrategy = BaseGridView.FOCUS_SCROLL_ALIGNED;
300    /**
301     * Defines how item view is aligned in the window.
302     */
303    private final WindowAlignment mWindowAlignment = new WindowAlignment();
304
305    /**
306     * Defines how item view is aligned.
307     */
308    private final ItemAlignment mItemAlignment = new ItemAlignment();
309
310    /**
311     * Dimensions of the view, width or height depending on orientation.
312     */
313    private int mSizePrimary;
314
315    /**
316     *  Allow DPAD key to navigate out at the front of the View (where position = 0),
317     *  default is false.
318     */
319    private boolean mFocusOutFront;
320
321    /**
322     * Allow DPAD key to navigate out at the end of the view, default is false.
323     */
324    private boolean mFocusOutEnd;
325
326    /**
327     * True if focus search is disabled.
328     */
329    private boolean mFocusSearchDisabled;
330
331    /**
332     * True if prune child,  might be disabled during transition.
333     */
334    private boolean mPruneChild = true;
335
336    /**
337     * True if scroll content,  might be disabled during transition.
338     */
339    private boolean mScrollEnabled = true;
340
341    private int[] mTempDeltas = new int[2];
342
343    /**
344     * Temporaries used for measuring.
345     */
346    private int[] mMeasuredDimension = new int[2];
347
348    final ViewsStateBundle mChildrenStates = new ViewsStateBundle();
349
350    public GridLayoutManager(BaseGridView baseGridView) {
351        mBaseGridView = baseGridView;
352    }
353
354    public void setOrientation(int orientation) {
355        if (orientation != HORIZONTAL && orientation != VERTICAL) {
356            if (DEBUG) Log.v(getTag(), "invalid orientation: " + orientation);
357            return;
358        }
359
360        mOrientation = orientation;
361        mWindowAlignment.setOrientation(orientation);
362        mItemAlignment.setOrientation(orientation);
363        mForceFullLayout = true;
364    }
365
366    public int getFocusScrollStrategy() {
367        return mFocusScrollStrategy;
368    }
369
370    public void setFocusScrollStrategy(int focusScrollStrategy) {
371        mFocusScrollStrategy = focusScrollStrategy;
372    }
373
374    public void setWindowAlignment(int windowAlignment) {
375        mWindowAlignment.mainAxis().setWindowAlignment(windowAlignment);
376    }
377
378    public int getWindowAlignment() {
379        return mWindowAlignment.mainAxis().getWindowAlignment();
380    }
381
382    public void setWindowAlignmentOffset(int alignmentOffset) {
383        mWindowAlignment.mainAxis().setWindowAlignmentOffset(alignmentOffset);
384    }
385
386    public int getWindowAlignmentOffset() {
387        return mWindowAlignment.mainAxis().getWindowAlignmentOffset();
388    }
389
390    public void setWindowAlignmentOffsetPercent(float offsetPercent) {
391        mWindowAlignment.mainAxis().setWindowAlignmentOffsetPercent(offsetPercent);
392    }
393
394    public float getWindowAlignmentOffsetPercent() {
395        return mWindowAlignment.mainAxis().getWindowAlignmentOffsetPercent();
396    }
397
398    public void setItemAlignmentOffset(int alignmentOffset) {
399        mItemAlignment.mainAxis().setItemAlignmentOffset(alignmentOffset);
400        updateChildAlignments();
401    }
402
403    public int getItemAlignmentOffset() {
404        return mItemAlignment.mainAxis().getItemAlignmentOffset();
405    }
406
407    public void setItemAlignmentOffsetWithPadding(boolean withPadding) {
408        mItemAlignment.mainAxis().setItemAlignmentOffsetWithPadding(withPadding);
409        updateChildAlignments();
410    }
411
412    public boolean isItemAlignmentOffsetWithPadding() {
413        return mItemAlignment.mainAxis().isItemAlignmentOffsetWithPadding();
414    }
415
416    public void setItemAlignmentOffsetPercent(float offsetPercent) {
417        mItemAlignment.mainAxis().setItemAlignmentOffsetPercent(offsetPercent);
418        updateChildAlignments();
419    }
420
421    public float getItemAlignmentOffsetPercent() {
422        return mItemAlignment.mainAxis().getItemAlignmentOffsetPercent();
423    }
424
425    public void setItemAlignmentViewId(int viewId) {
426        mItemAlignment.mainAxis().setItemAlignmentViewId(viewId);
427        updateChildAlignments();
428    }
429
430    public int getItemAlignmentViewId() {
431        return mItemAlignment.mainAxis().getItemAlignmentViewId();
432    }
433
434    public void setFocusOutAllowed(boolean throughFront, boolean throughEnd) {
435        mFocusOutFront = throughFront;
436        mFocusOutEnd = throughEnd;
437    }
438
439    public void setNumRows(int numRows) {
440        if (numRows < 0) throw new IllegalArgumentException();
441        mNumRowsRequested = numRows;
442        mForceFullLayout = true;
443    }
444
445    /**
446     * Set the row height. May be WRAP_CONTENT, or a size in pixels.
447     */
448    public void setRowHeight(int height) {
449        if (height >= 0 || height == ViewGroup.LayoutParams.WRAP_CONTENT) {
450            mRowSizeSecondaryRequested = height;
451        } else {
452            throw new IllegalArgumentException("Invalid row height: " + height);
453        }
454    }
455
456    public void setItemMargin(int margin) {
457        mVerticalMargin = mHorizontalMargin = margin;
458        mMarginPrimary = mMarginSecondary = margin;
459    }
460
461    public void setVerticalMargin(int margin) {
462        if (mOrientation == HORIZONTAL) {
463            mMarginSecondary = mVerticalMargin = margin;
464        } else {
465            mMarginPrimary = mVerticalMargin = margin;
466        }
467    }
468
469    public void setHorizontalMargin(int margin) {
470        if (mOrientation == HORIZONTAL) {
471            mMarginPrimary = mHorizontalMargin = margin;
472        } else {
473            mMarginSecondary = mHorizontalMargin = margin;
474        }
475    }
476
477    public int getVerticalMargin() {
478        return mVerticalMargin;
479    }
480
481    public int getHorizontalMargin() {
482        return mHorizontalMargin;
483    }
484
485    public void setGravity(int gravity) {
486        mGravity = gravity;
487    }
488
489    protected boolean hasDoneFirstLayout() {
490        return mGrid != null;
491    }
492
493    public void setOnChildSelectedListener(OnChildSelectedListener listener) {
494        mChildSelectedListener = listener;
495    }
496
497    private int getPositionByView(View view) {
498        if (view == null) {
499            return NO_POSITION;
500        }
501        LayoutParams params = (LayoutParams) view.getLayoutParams();
502        if (params == null || params.isItemRemoved()) {
503            // when item is removed, the position value can be any value.
504            return NO_POSITION;
505        }
506        return params.getViewPosition();
507    }
508
509    private int getPositionByIndex(int index) {
510        return getPositionByView(getChildAt(index));
511    }
512
513    private void dispatchChildSelected() {
514        if (mChildSelectedListener == null) {
515            return;
516        }
517        if (mFocusPosition != NO_POSITION) {
518            View view = findViewByPosition(mFocusPosition);
519            if (view != null) {
520                RecyclerView.ViewHolder vh = mBaseGridView.getChildViewHolder(view);
521                mChildSelectedListener.onChildSelected(mBaseGridView, view, mFocusPosition,
522                        vh == null? NO_ID: vh.getItemId());
523                return;
524            }
525        }
526        mChildSelectedListener.onChildSelected(mBaseGridView, null, NO_POSITION, NO_ID);
527    }
528
529    @Override
530    public boolean canScrollHorizontally() {
531        // We can scroll horizontally if we have horizontal orientation, or if
532        // we are vertical and have more than one column.
533        return mOrientation == HORIZONTAL || mNumRows > 1;
534    }
535
536    @Override
537    public boolean canScrollVertically() {
538        // We can scroll vertically if we have vertical orientation, or if we
539        // are horizontal and have more than one row.
540        return mOrientation == VERTICAL || mNumRows > 1;
541    }
542
543    @Override
544    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
545        return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
546                ViewGroup.LayoutParams.WRAP_CONTENT);
547    }
548
549    @Override
550    public RecyclerView.LayoutParams generateLayoutParams(Context context, AttributeSet attrs) {
551        return new LayoutParams(context, attrs);
552    }
553
554    @Override
555    public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
556        if (lp instanceof LayoutParams) {
557            return new LayoutParams((LayoutParams) lp);
558        } else if (lp instanceof RecyclerView.LayoutParams) {
559            return new LayoutParams((RecyclerView.LayoutParams) lp);
560        } else if (lp instanceof MarginLayoutParams) {
561            return new LayoutParams((MarginLayoutParams) lp);
562        } else {
563            return new LayoutParams(lp);
564        }
565    }
566
567    protected View getViewForPosition(int position) {
568        return mRecycler.getViewForPosition(position);
569    }
570
571    final int getOpticalLeft(View v) {
572        return ((LayoutParams) v.getLayoutParams()).getOpticalLeft(v);
573    }
574
575    final int getOpticalRight(View v) {
576        return ((LayoutParams) v.getLayoutParams()).getOpticalRight(v);
577    }
578
579    final int getOpticalTop(View v) {
580        return ((LayoutParams) v.getLayoutParams()).getOpticalTop(v);
581    }
582
583    final int getOpticalBottom(View v) {
584        return ((LayoutParams) v.getLayoutParams()).getOpticalBottom(v);
585    }
586
587    private int getViewMin(View v) {
588        return (mOrientation == HORIZONTAL) ? getOpticalLeft(v) : getOpticalTop(v);
589    }
590
591    private int getViewMax(View v) {
592        return (mOrientation == HORIZONTAL) ? getOpticalRight(v) : getOpticalBottom(v);
593    }
594
595    private int getViewCenter(View view) {
596        return (mOrientation == HORIZONTAL) ? getViewCenterX(view) : getViewCenterY(view);
597    }
598
599    private int getViewCenterSecondary(View view) {
600        return (mOrientation == HORIZONTAL) ? getViewCenterY(view) : getViewCenterX(view);
601    }
602
603    private int getViewCenterX(View v) {
604        LayoutParams p = (LayoutParams) v.getLayoutParams();
605        return p.getOpticalLeft(v) + p.getAlignX();
606    }
607
608    private int getViewCenterY(View v) {
609        LayoutParams p = (LayoutParams) v.getLayoutParams();
610        return p.getOpticalTop(v) + p.getAlignY();
611    }
612
613    /**
614     * Save Recycler and State for convenience.  Must be paired with leaveContext().
615     */
616    private void saveContext(Recycler recycler, State state) {
617        if (mRecycler != null || mState != null) {
618            Log.e(TAG, "Recycler information was not released, bug!");
619        }
620        mRecycler = recycler;
621        mState = state;
622    }
623
624    /**
625     * Discard saved Recycler and State.
626     */
627    private void leaveContext() {
628        mRecycler = null;
629        mState = null;
630    }
631
632    /**
633     * Re-initialize data structures for a data change or handling invisible
634     * selection. The method tries its best to preserve position information so
635     * that staggered grid looks same before and after re-initialize.
636     * @param focusPosition The initial focusPosition that we would like to
637     *        focus on.
638     * @return Actual position that can be focused on.
639     */
640    private int init(int focusPosition) {
641
642        final int newItemCount = mState.getItemCount();
643
644        if (focusPosition == NO_POSITION && newItemCount > 0) {
645            // if focus position is never set before,  initialize it to 0
646            focusPosition = 0;
647        }
648        // If adapter has changed then caches are invalid; otherwise,
649        // we try to maintain each row's position if number of rows keeps the same
650        // and existing mGrid contains the focusPosition.
651        if (mRows != null && mNumRows == mRows.length &&
652                mGrid != null && mGrid.getSize() > 0 && focusPosition >= 0 &&
653                focusPosition >= mGrid.getFirstIndex() &&
654                focusPosition <= mGrid.getLastIndex()) {
655            // strip mGrid to a subset (like a column) that contains focusPosition
656            mGrid.stripDownTo(focusPosition);
657            // make sure that remaining items do not exceed new adapter size
658            int firstIndex = mGrid.getFirstIndex();
659            int lastIndex = mGrid.getLastIndex();
660            if (DEBUG) {
661                Log .v(getTag(), "mGrid firstIndex " + firstIndex + " lastIndex " + lastIndex);
662            }
663            for (int i = lastIndex; i >=firstIndex; i--) {
664                if (i >= newItemCount) {
665                    mGrid.removeLast();
666                }
667            }
668            if (mGrid.getSize() == 0) {
669                focusPosition = newItemCount - 1;
670                // initialize row start locations
671                for (int i = 0; i < mNumRows; i++) {
672                    mRows[i].low = 0;
673                    mRows[i].high = 0;
674                }
675                if (DEBUG) Log.v(getTag(), "mGrid zero size");
676            } else {
677                // initialize row start locations
678                for (int i = 0; i < mNumRows; i++) {
679                    mRows[i].low = Integer.MAX_VALUE;
680                    mRows[i].high = Integer.MIN_VALUE;
681                }
682                firstIndex = mGrid.getFirstIndex();
683                lastIndex = mGrid.getLastIndex();
684                if (focusPosition > lastIndex) {
685                    focusPosition = mGrid.getLastIndex();
686                }
687                if (DEBUG) {
688                    Log.v(getTag(), "mGrid firstIndex " + firstIndex + " lastIndex "
689                        + lastIndex + " focusPosition " + focusPosition);
690                }
691                // fill rows with minimal view positions of the subset
692                for (int i = firstIndex; i <= lastIndex; i++) {
693                    View v = findViewByPosition(i);
694                    if (v == null) {
695                        continue;
696                    }
697                    int row = mGrid.getLocation(i).row;
698                    int low = getViewMin(v) + mScrollOffsetPrimary;
699                    if (low < mRows[row].low) {
700                        mRows[row].low = mRows[row].high = low;
701                    }
702                }
703                int firstItemRowPosition = mRows[mGrid.getLocation(firstIndex).row].low;
704                if (firstItemRowPosition == Integer.MAX_VALUE) {
705                    firstItemRowPosition = 0;
706                }
707                if (mState.didStructureChange()) {
708                    // if there is structure change, the removed item might be in the
709                    // subset,  so it is meaningless to maintain the low locations.
710                    for (int i = 0; i < mNumRows; i++) {
711                        mRows[i].low = firstItemRowPosition;
712                        mRows[i].high = firstItemRowPosition;
713                    }
714                } else {
715                    // fill other rows that does not include the subset using first item
716                    for (int i = 0; i < mNumRows; i++) {
717                        if (mRows[i].low == Integer.MAX_VALUE) {
718                            mRows[i].low = mRows[i].high = firstItemRowPosition;
719                        }
720                    }
721                }
722            }
723
724            // Same adapter, we can reuse any attached views
725            detachAndScrapAttachedViews(mRecycler);
726
727        } else {
728            // otherwise recreate data structure
729            mRows = new StaggeredGrid.Row[mNumRows];
730
731            for (int i = 0; i < mNumRows; i++) {
732                mRows[i] = new StaggeredGrid.Row();
733            }
734            mGrid = new StaggeredGridDefault();
735            if (newItemCount == 0) {
736                focusPosition = NO_POSITION;
737            } else if (focusPosition >= newItemCount) {
738                focusPosition = newItemCount - 1;
739            }
740
741            // Adapter may have changed so remove all attached views permanently
742            removeAndRecycleAllViews(mRecycler);
743
744            mScrollOffsetPrimary = 0;
745            mScrollOffsetSecondary = 0;
746            mWindowAlignment.reset();
747        }
748
749        mGrid.setProvider(mGridProvider);
750        // mGrid share the same Row array information
751        mGrid.setRows(mRows);
752        mFirstVisiblePos = mLastVisiblePos = NO_POSITION;
753
754        initScrollController();
755        updateScrollSecondAxis();
756
757        return focusPosition;
758    }
759
760    private int getRowSizeSecondary(int rowIndex) {
761        if (mFixedRowSizeSecondary != 0) {
762            return mFixedRowSizeSecondary;
763        }
764        if (mRowSizeSecondary == null) {
765            return 0;
766        }
767        return mRowSizeSecondary[rowIndex];
768    }
769
770    private int getRowStartSecondary(int rowIndex) {
771        int start = 0;
772        for (int i = 0; i < rowIndex; i++) {
773            start += getRowSizeSecondary(i) + mMarginSecondary;
774        }
775        return start;
776    }
777
778    private int getSizeSecondary() {
779        return getRowStartSecondary(mNumRows - 1) + getRowSizeSecondary(mNumRows - 1);
780    }
781
782    private void measureScrapChild(int position, int widthSpec, int heightSpec,
783            int[] measuredDimension) {
784        View view = mRecycler.getViewForPosition(position);
785        if (view != null) {
786            LayoutParams p = (LayoutParams) view.getLayoutParams();
787            int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
788                    getPaddingLeft() + getPaddingRight(), p.width);
789            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
790                    getPaddingTop() + getPaddingBottom(), p.height);
791            view.measure(childWidthSpec, childHeightSpec);
792            measuredDimension[0] = view.getMeasuredWidth();
793            measuredDimension[1] = view.getMeasuredHeight();
794            mRecycler.recycleView(view);
795        }
796    }
797
798    private boolean processRowSizeSecondary(boolean measure) {
799        if (mFixedRowSizeSecondary != 0) {
800            return false;
801        }
802
803        List<Integer>[] rows = mGrid == null ? null :
804            mGrid.getItemPositionsInRows(mFirstVisiblePos, mLastVisiblePos);
805        boolean changed = false;
806        int scrapChildWidth = -1;
807        int scrapChildHeight = -1;
808
809        for (int rowIndex = 0; rowIndex < mNumRows; rowIndex++) {
810            final int rowItemCount = rows == null ? 0 : rows[rowIndex].size();
811            if (DEBUG) Log.v(getTag(), "processRowSizeSecondary row " + rowIndex +
812                    " rowItemCount " + rowItemCount);
813
814            int rowSize = -1;
815            for (int i = 0; i < rowItemCount; i++) {
816                final View view = findViewByPosition(rows[rowIndex].get(i));
817                if (view == null) {
818                    continue;
819                }
820                if (measure && view.isLayoutRequested()) {
821                    measureChild(view);
822                }
823                final int secondarySize = mOrientation == HORIZONTAL ?
824                        view.getMeasuredHeight() : view.getMeasuredWidth();
825                if (secondarySize > rowSize) {
826                    rowSize = secondarySize;
827                }
828            }
829
830            if (measure && rowSize < 0 && mState.getItemCount() > 0) {
831                if (scrapChildWidth < 0 && scrapChildHeight < 0) {
832                    measureScrapChild(mFocusPosition == NO_POSITION ? 0 : mFocusPosition,
833                            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
834                            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
835                            mMeasuredDimension);
836                    scrapChildWidth = mMeasuredDimension[0];
837                    scrapChildHeight = mMeasuredDimension[1];
838                    if (DEBUG) Log.v(TAG, "measured scrap child: " + scrapChildWidth +
839                            " " + scrapChildHeight);
840                }
841                rowSize = mOrientation == HORIZONTAL ? scrapChildHeight : scrapChildWidth;
842            }
843
844            if (rowSize < 0) {
845                rowSize = 0;
846            }
847
848            if (DEBUG) Log.v(getTag(), "row " + rowIndex + " rowItemCount " + rowItemCount +
849                    " rowSize " + rowSize);
850
851            if (mRowSizeSecondary[rowIndex] != rowSize) {
852                if (DEBUG) Log.v(getTag(), "row size secondary changed: " + mRowSizeSecondary[rowIndex] +
853                        ", " + rowSize);
854
855                mRowSizeSecondary[rowIndex] = rowSize;
856                changed = true;
857            }
858        }
859
860        return changed;
861    }
862
863    /**
864     * Checks if we need to update row secondary sizes.
865     */
866    private void updateRowSecondarySizeRefresh() {
867        mRowSecondarySizeRefresh = processRowSizeSecondary(false);
868        if (mRowSecondarySizeRefresh) {
869            if (DEBUG) Log.v(getTag(), "mRowSecondarySizeRefresh now set");
870            forceRequestLayout();
871        }
872    }
873
874    private void forceRequestLayout() {
875        if (DEBUG) Log.v(getTag(), "forceRequestLayout");
876        // RecyclerView prevents us from requesting layout in many cases
877        // (during layout, during scroll, etc.)
878        // For secondary row size wrap_content support we currently need a
879        // second layout pass to update the measured size after having measured
880        // and added child views in layoutChildren.
881        // Force the second layout by posting a delayed runnable.
882        // TODO: investigate allowing a second layout pass,
883        // or move child add/measure logic to the measure phase.
884        ViewCompat.postOnAnimation(mBaseGridView, mRequestLayoutRunnable);
885    }
886
887    private final Runnable mRequestLayoutRunnable = new Runnable() {
888        @Override
889        public void run() {
890            if (DEBUG) Log.v(getTag(), "request Layout from runnable");
891            requestLayout();
892        }
893     };
894
895    @Override
896    public void onMeasure(Recycler recycler, State state, int widthSpec, int heightSpec) {
897        saveContext(recycler, state);
898
899        int sizePrimary, sizeSecondary, modeSecondary, paddingSecondary;
900        int measuredSizeSecondary;
901        if (mOrientation == HORIZONTAL) {
902            sizePrimary = MeasureSpec.getSize(widthSpec);
903            sizeSecondary = MeasureSpec.getSize(heightSpec);
904            modeSecondary = MeasureSpec.getMode(heightSpec);
905            paddingSecondary = getPaddingTop() + getPaddingBottom();
906        } else {
907            sizeSecondary = MeasureSpec.getSize(widthSpec);
908            sizePrimary = MeasureSpec.getSize(heightSpec);
909            modeSecondary = MeasureSpec.getMode(widthSpec);
910            paddingSecondary = getPaddingLeft() + getPaddingRight();
911        }
912        if (DEBUG) Log.v(getTag(), "onMeasure widthSpec " + Integer.toHexString(widthSpec) +
913                " heightSpec " + Integer.toHexString(heightSpec) +
914                " modeSecondary " + Integer.toHexString(modeSecondary) +
915                " sizeSecondary " + sizeSecondary + " " + this);
916
917        mMaxSizeSecondary = sizeSecondary;
918
919        if (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) {
920            mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested;
921            mFixedRowSizeSecondary = 0;
922
923            if (mRowSizeSecondary == null || mRowSizeSecondary.length != mNumRows) {
924                mRowSizeSecondary = new int[mNumRows];
925            }
926
927            // Measure all current children and update cached row heights
928            processRowSizeSecondary(true);
929
930            switch (modeSecondary) {
931            case MeasureSpec.UNSPECIFIED:
932                measuredSizeSecondary = getSizeSecondary() + paddingSecondary;
933                break;
934            case MeasureSpec.AT_MOST:
935                measuredSizeSecondary = Math.min(getSizeSecondary() + paddingSecondary,
936                        mMaxSizeSecondary);
937                break;
938            case MeasureSpec.EXACTLY:
939                measuredSizeSecondary = mMaxSizeSecondary;
940                break;
941            default:
942                throw new IllegalStateException("wrong spec");
943            }
944
945        } else {
946            switch (modeSecondary) {
947            case MeasureSpec.UNSPECIFIED:
948                if (mRowSizeSecondaryRequested == 0) {
949                    if (mOrientation == HORIZONTAL) {
950                        throw new IllegalStateException("Must specify rowHeight or view height");
951                    } else {
952                        throw new IllegalStateException("Must specify columnWidth or view width");
953                    }
954                }
955                mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
956                mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested;
957                measuredSizeSecondary = mFixedRowSizeSecondary * mNumRows + mMarginSecondary
958                    * (mNumRows - 1) + paddingSecondary;
959                break;
960            case MeasureSpec.AT_MOST:
961            case MeasureSpec.EXACTLY:
962                if (mNumRowsRequested == 0 && mRowSizeSecondaryRequested == 0) {
963                    mNumRows = 1;
964                    mFixedRowSizeSecondary = sizeSecondary - paddingSecondary;
965                } else if (mNumRowsRequested == 0) {
966                    mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
967                    mNumRows = (sizeSecondary + mMarginSecondary)
968                        / (mRowSizeSecondaryRequested + mMarginSecondary);
969                } else if (mRowSizeSecondaryRequested == 0) {
970                    mNumRows = mNumRowsRequested;
971                    mFixedRowSizeSecondary = (sizeSecondary - paddingSecondary - mMarginSecondary
972                            * (mNumRows - 1)) / mNumRows;
973                } else {
974                    mNumRows = mNumRowsRequested;
975                    mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
976                }
977                measuredSizeSecondary = sizeSecondary;
978                if (modeSecondary == MeasureSpec.AT_MOST) {
979                    int childrenSize = mFixedRowSizeSecondary * mNumRows + mMarginSecondary
980                        * (mNumRows - 1) + paddingSecondary;
981                    if (childrenSize < measuredSizeSecondary) {
982                        measuredSizeSecondary = childrenSize;
983                    }
984                }
985                break;
986            default:
987                throw new IllegalStateException("wrong spec");
988            }
989        }
990        if (mOrientation == HORIZONTAL) {
991            setMeasuredDimension(sizePrimary, measuredSizeSecondary);
992        } else {
993            setMeasuredDimension(measuredSizeSecondary, sizePrimary);
994        }
995        if (DEBUG) {
996            Log.v(getTag(), "onMeasure sizePrimary " + sizePrimary +
997                    " measuredSizeSecondary " + measuredSizeSecondary +
998                    " mFixedRowSizeSecondary " + mFixedRowSizeSecondary +
999                    " mNumRows " + mNumRows);
1000        }
1001
1002        leaveContext();
1003    }
1004
1005    private void measureChild(View child) {
1006        final ViewGroup.LayoutParams lp = child.getLayoutParams();
1007        final int secondarySpec = (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) ?
1008                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) :
1009                MeasureSpec.makeMeasureSpec(mFixedRowSizeSecondary, MeasureSpec.EXACTLY);
1010        int widthSpec, heightSpec;
1011
1012        if (mOrientation == HORIZONTAL) {
1013            widthSpec = ViewGroup.getChildMeasureSpec(
1014                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
1015                    0, lp.width);
1016            heightSpec = ViewGroup.getChildMeasureSpec(secondarySpec, 0, lp.height);
1017        } else {
1018            heightSpec = ViewGroup.getChildMeasureSpec(
1019                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
1020                    0, lp.height);
1021            widthSpec = ViewGroup.getChildMeasureSpec(secondarySpec, 0, lp.width);
1022        }
1023
1024        child.measure(widthSpec, heightSpec);
1025
1026        if (DEBUG) Log.v(getTag(), "measureChild secondarySpec " + Integer.toHexString(secondarySpec) +
1027                " widthSpec " + Integer.toHexString(widthSpec) +
1028                " heightSpec " + Integer.toHexString(heightSpec) +
1029                " measuredWidth " + child.getMeasuredWidth() +
1030                " measuredHeight " + child.getMeasuredHeight());
1031        if (DEBUG) Log.v(getTag(), "child lp width " + lp.width + " height " + lp.height);
1032    }
1033
1034    private StaggeredGrid.Provider mGridProvider = new StaggeredGrid.Provider() {
1035
1036        @Override
1037        public int getCount() {
1038            return mState.getItemCount();
1039        }
1040
1041        @Override
1042        public void createItem(int index, int rowIndex, boolean append) {
1043            View v = getViewForPosition(index);
1044            if (mFirstVisiblePos >= 0) {
1045                // when StaggeredGrid append or prepend item, we must guarantee
1046                // that sibling item has created views already.
1047                if (append && index != mLastVisiblePos + 1) {
1048                    throw new RuntimeException();
1049                } else if (!append && index != mFirstVisiblePos - 1) {
1050                    throw new RuntimeException();
1051                }
1052            }
1053
1054            // See recyclerView docs:  we don't need re-add scraped view if it was removed.
1055            if (!((RecyclerView.LayoutParams) v.getLayoutParams()).isItemRemoved()) {
1056                if (append) {
1057                    addView(v);
1058                } else {
1059                    addView(v, 0);
1060                }
1061
1062                // View is added first or it won't be found by dispatchChildSelected.
1063                if (mInLayout && index == mFocusPosition) {
1064                    dispatchChildSelected();
1065                }
1066
1067                measureChild(v);
1068            }
1069
1070            int length = mOrientation == HORIZONTAL ? v.getMeasuredWidth() : v.getMeasuredHeight();
1071            int start, end;
1072            final boolean rowIsEmpty = mRows[rowIndex].high == mRows[rowIndex].low;
1073            if (append) {
1074                if (!rowIsEmpty) {
1075                    // if there are existing item in the row,  add margin between
1076                    start = mRows[rowIndex].high + mMarginPrimary;
1077                } else {
1078                    if (mLastVisiblePos >= 0) {
1079                        int lastRow = mGrid.getLocation(mLastVisiblePos).row;
1080                        // if the last visible item is not last row,  align to beginning,
1081                        // otherwise start a new column after.
1082                        if (lastRow < mNumRows - 1) {
1083                            start = mRows[lastRow].low;
1084                        } else {
1085                            start = mRows[lastRow].high + mMarginPrimary;
1086                        }
1087                    } else {
1088                        start = 0;
1089                    }
1090                    mRows[rowIndex].low = start;
1091                }
1092                end = start + length;
1093                mRows[rowIndex].high = end;
1094            } else {
1095                if (!rowIsEmpty) {
1096                    // if there are existing item in the row,  add margin between
1097                    end = mRows[rowIndex].low - mMarginPrimary;
1098                    start = end - length;
1099                } else {
1100                    if (mFirstVisiblePos >= 0) {
1101                        int firstRow = mGrid.getLocation(mFirstVisiblePos).row;
1102                        // if the first visible item is not first row,  align to beginning,
1103                        // otherwise start a new column before.
1104                        if (firstRow > 0) {
1105                            start = mRows[firstRow].low;
1106                            end = start + length;
1107                        } else {
1108                            end = mRows[firstRow].low - mMarginPrimary;
1109                            start = end - length;
1110                        }
1111                    } else {
1112                        start = 0;
1113                        end = length;
1114                    }
1115                    mRows[rowIndex].high = end;
1116                }
1117                mRows[rowIndex].low = start;
1118            }
1119            if (mFirstVisiblePos < 0) {
1120                mFirstVisiblePos = mLastVisiblePos = index;
1121            } else {
1122                if (append) {
1123                    mLastVisiblePos++;
1124                } else {
1125                    mFirstVisiblePos--;
1126                }
1127            }
1128            if (DEBUG) Log.v(getTag(), "start " + start + " end " + end);
1129            int startSecondary = getRowStartSecondary(rowIndex) - mScrollOffsetSecondary;
1130            mChildrenStates.loadView(v, index);
1131            layoutChild(rowIndex, v, start - mScrollOffsetPrimary, end - mScrollOffsetPrimary,
1132                    startSecondary);
1133            if (DEBUG) {
1134                Log.d(getTag(), "addView " + index + " " + v);
1135            }
1136            if (index == mFirstVisiblePos) {
1137                updateScrollMin();
1138            }
1139            if (index == mLastVisiblePos) {
1140                updateScrollMax();
1141            }
1142        }
1143    };
1144
1145    private void layoutChild(int rowIndex, View v, int start, int end, int startSecondary) {
1146        int sizeSecondary = mOrientation == HORIZONTAL ? v.getMeasuredHeight()
1147                : v.getMeasuredWidth();
1148        if (mFixedRowSizeSecondary > 0) {
1149            sizeSecondary = Math.min(sizeSecondary, mFixedRowSizeSecondary);
1150        }
1151        final int verticalGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
1152        final int horizontalGravity = mGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
1153        if (mOrientation == HORIZONTAL && verticalGravity == Gravity.TOP
1154                || mOrientation == VERTICAL && horizontalGravity == Gravity.LEFT) {
1155            // do nothing
1156        } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.BOTTOM
1157                || mOrientation == VERTICAL && horizontalGravity == Gravity.RIGHT) {
1158            startSecondary += getRowSizeSecondary(rowIndex) - sizeSecondary;
1159        } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.CENTER_VERTICAL
1160                || mOrientation == VERTICAL && horizontalGravity == Gravity.CENTER_HORIZONTAL) {
1161            startSecondary += (getRowSizeSecondary(rowIndex) - sizeSecondary) / 2;
1162        }
1163        int left, top, right, bottom;
1164        if (mOrientation == HORIZONTAL) {
1165            left = start;
1166            top = startSecondary;
1167            right = end;
1168            bottom = startSecondary + sizeSecondary;
1169        } else {
1170            top = start;
1171            left = startSecondary;
1172            bottom = end;
1173            right = startSecondary + sizeSecondary;
1174        }
1175        v.layout(left, top, right, bottom);
1176        updateChildOpticalInsets(v, left, top, right, bottom);
1177        updateChildAlignments(v);
1178    }
1179
1180    private void updateChildOpticalInsets(View v, int left, int top, int right, int bottom) {
1181        LayoutParams p = (LayoutParams) v.getLayoutParams();
1182        p.setOpticalInsets(left - v.getLeft(), top - v.getTop(),
1183                v.getRight() - right, v.getBottom() - bottom);
1184    }
1185
1186    private void updateChildAlignments(View v) {
1187        LayoutParams p = (LayoutParams) v.getLayoutParams();
1188        p.setAlignX(mItemAlignment.horizontal.getAlignmentPosition(v));
1189        p.setAlignY(mItemAlignment.vertical.getAlignmentPosition(v));
1190    }
1191
1192    private void updateChildAlignments() {
1193        for (int i = 0, c = getChildCount(); i < c; i++) {
1194            updateChildAlignments(getChildAt(i));
1195        }
1196    }
1197
1198    private boolean needsAppendVisibleItem() {
1199        if (mLastVisiblePos < mFocusPosition) {
1200            return true;
1201        }
1202        int right = mScrollOffsetPrimary + mSizePrimary;
1203        for (int i = 0; i < mNumRows; i++) {
1204            if (mRows[i].low == mRows[i].high) {
1205                if (mRows[i].high < right) {
1206                    return true;
1207                }
1208            } else if (mRows[i].high < right - mMarginPrimary) {
1209                return true;
1210            }
1211        }
1212        return false;
1213    }
1214
1215    private boolean needsPrependVisibleItem() {
1216        if (mFirstVisiblePos > mFocusPosition) {
1217            return true;
1218        }
1219        for (int i = 0; i < mNumRows; i++) {
1220            if (mRows[i].low == mRows[i].high) {
1221                if (mRows[i].low > mScrollOffsetPrimary) {
1222                    return true;
1223                }
1224            } else if (mRows[i].low - mMarginPrimary > mScrollOffsetPrimary) {
1225                return true;
1226            }
1227        }
1228        return false;
1229    }
1230
1231    // Append one column if possible and return true if reach end.
1232    private boolean appendOneVisibleItem() {
1233        while (true) {
1234            if (mLastVisiblePos != NO_POSITION && mLastVisiblePos < mState.getItemCount() -1 &&
1235                    mLastVisiblePos < mGrid.getLastIndex()) {
1236                // append invisible view of saved location till last row
1237                final int index = mLastVisiblePos + 1;
1238                final int row = mGrid.getLocation(index).row;
1239                mGridProvider.createItem(index, row, true);
1240                if (row == mNumRows - 1) {
1241                    return false;
1242                }
1243            } else if ((mLastVisiblePos == NO_POSITION && mState.getItemCount() > 0) ||
1244                    (mLastVisiblePos != NO_POSITION &&
1245                            mLastVisiblePos < mState.getItemCount() - 1)) {
1246                mGrid.appendItems(mScrollOffsetPrimary + mSizePrimary);
1247                return false;
1248            } else {
1249                return true;
1250            }
1251        }
1252    }
1253
1254    private void appendVisibleItems() {
1255        while (needsAppendVisibleItem()) {
1256            if (appendOneVisibleItem()) {
1257                break;
1258            }
1259        }
1260    }
1261
1262    // Prepend one column if possible and return true if reach end.
1263    private boolean prependOneVisibleItem() {
1264        while (true) {
1265            if (mFirstVisiblePos > 0) {
1266                if (mFirstVisiblePos > mGrid.getFirstIndex()) {
1267                    // prepend invisible view of saved location till first row
1268                    final int index = mFirstVisiblePos - 1;
1269                    final int row = mGrid.getLocation(index).row;
1270                    mGridProvider.createItem(index, row, false);
1271                    if (row == 0) {
1272                        return false;
1273                    }
1274                } else {
1275                    mGrid.prependItems(mScrollOffsetPrimary);
1276                    return false;
1277                }
1278            } else {
1279                return true;
1280            }
1281        }
1282    }
1283
1284    private void prependVisibleItems() {
1285        while (needsPrependVisibleItem()) {
1286            if (prependOneVisibleItem()) {
1287                break;
1288            }
1289        }
1290    }
1291
1292    private void removeChildAt(int position) {
1293        View v = findViewByPosition(position);
1294        if (v != null) {
1295            if (DEBUG) {
1296                Log.d(getTag(), "removeAndRecycleViewAt " + position);
1297            }
1298            mChildrenStates.saveOffscreenView(v, position);
1299            removeAndRecycleView(v, mRecycler);
1300        }
1301    }
1302
1303    private void removeInvisibleViewsAtEnd() {
1304        if (!mPruneChild) {
1305            return;
1306        }
1307        boolean update = false;
1308        while(mLastVisiblePos > mFirstVisiblePos && mLastVisiblePos > mFocusPosition) {
1309            View view = findViewByPosition(mLastVisiblePos);
1310            if (getViewMin(view) > mSizePrimary) {
1311                removeChildAt(mLastVisiblePos);
1312                mLastVisiblePos--;
1313                update = true;
1314            } else {
1315                break;
1316            }
1317        }
1318        if (update) {
1319            updateRowsMinMax();
1320        }
1321    }
1322
1323    private void removeInvisibleViewsAtFront() {
1324        if (!mPruneChild) {
1325            return;
1326        }
1327        boolean update = false;
1328        while(mLastVisiblePos > mFirstVisiblePos && mFirstVisiblePos < mFocusPosition) {
1329            View view = findViewByPosition(mFirstVisiblePos);
1330            if (getViewMax(view) < 0) {
1331                removeChildAt(mFirstVisiblePos);
1332                mFirstVisiblePos++;
1333                update = true;
1334            } else {
1335                break;
1336            }
1337        }
1338        if (update) {
1339            updateRowsMinMax();
1340        }
1341    }
1342
1343    private void updateRowsMinMax() {
1344        if (mFirstVisiblePos < 0) {
1345            return;
1346        }
1347        for (int i = 0; i < mNumRows; i++) {
1348            mRows[i].low = Integer.MAX_VALUE;
1349            mRows[i].high = Integer.MIN_VALUE;
1350        }
1351        for (int i = mFirstVisiblePos; i <= mLastVisiblePos; i++) {
1352            View view = findViewByPosition(i);
1353            int row = mGrid.getLocation(i).row;
1354            int low = getViewMin(view) + mScrollOffsetPrimary;
1355            if (low < mRows[row].low) {
1356                mRows[row].low = low;
1357            }
1358            int high = getViewMax(view) + mScrollOffsetPrimary;
1359            if (high > mRows[row].high) {
1360                mRows[row].high = high;
1361            }
1362        }
1363    }
1364
1365    // Fast layout when there is no structure change, adapter change, etc.
1366    protected void fastRelayout(boolean scrollToFocus) {
1367        initScrollController();
1368
1369        List<Integer>[] rows = mGrid.getItemPositionsInRows(mFirstVisiblePos, mLastVisiblePos);
1370
1371        // relayout and repositioning views on each row
1372        for (int i = 0; i < mNumRows; i++) {
1373            List<Integer> row = rows[i];
1374            final int startSecondary = getRowStartSecondary(i) - mScrollOffsetSecondary;
1375            for (int j = 0, size = row.size(); j < size; j++) {
1376                final int position = row.get(j);
1377                final View view = findViewByPosition(position);
1378                int primaryDelta, start, end;
1379
1380                if (mOrientation == HORIZONTAL) {
1381                    final int primarySize = view.getMeasuredWidth();
1382                    if (view.isLayoutRequested()) {
1383                        measureChild(view);
1384                    }
1385                    start = getViewMin(view);
1386                    end = start + view.getMeasuredWidth();
1387                    primaryDelta = view.getMeasuredWidth() - primarySize;
1388                    if (primaryDelta != 0) {
1389                        for (int k = j + 1; k < size; k++) {
1390                            findViewByPosition(row.get(k)).offsetLeftAndRight(primaryDelta);
1391                        }
1392                    }
1393                } else {
1394                    final int primarySize = view.getMeasuredHeight();
1395                    if (view.isLayoutRequested()) {
1396                        measureChild(view);
1397                    }
1398                    start = getViewMin(view);
1399                    end = start + view.getMeasuredHeight();
1400                    primaryDelta = view.getMeasuredHeight() - primarySize;
1401                    if (primaryDelta != 0) {
1402                        for (int k = j + 1; k < size; k++) {
1403                            findViewByPosition(row.get(k)).offsetTopAndBottom(primaryDelta);
1404                        }
1405                    }
1406                }
1407                layoutChild(i, view, start, end, startSecondary);
1408            }
1409        }
1410
1411        updateRowsMinMax();
1412        appendVisibleItems();
1413        prependVisibleItems();
1414
1415        updateRowsMinMax();
1416        updateScrollMin();
1417        updateScrollMax();
1418        updateScrollSecondAxis();
1419
1420        if (scrollToFocus) {
1421            View focusView = findViewByPosition(mFocusPosition == NO_POSITION ? 0 : mFocusPosition);
1422            scrollToView(focusView, false);
1423        }
1424    }
1425
1426    public void removeAndRecycleAllViews(RecyclerView.Recycler recycler) {
1427        if (DEBUG) Log.v(TAG, "removeAndRecycleAllViews " + getChildCount());
1428        for (int i = getChildCount() - 1; i >= 0; i--) {
1429            removeAndRecycleViewAt(i, recycler);
1430        }
1431    }
1432
1433    // Lays out items based on the current scroll position
1434    @Override
1435    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
1436        if (DEBUG) {
1437            Log.v(getTag(), "layoutChildren start numRows " + mNumRows + " mScrollOffsetSecondary "
1438                    + mScrollOffsetSecondary + " mScrollOffsetPrimary " + mScrollOffsetPrimary
1439                    + " inPreLayout " + state.isPreLayout()
1440                    + " didStructureChange " + state.didStructureChange()
1441                    + " mForceFullLayout " + mForceFullLayout);
1442            Log.v(getTag(), "width " + getWidth() + " height " + getHeight());
1443        }
1444
1445        if (mNumRows == 0) {
1446            // haven't done measure yet
1447            return;
1448        }
1449        final int itemCount = state.getItemCount();
1450        if (itemCount < 0) {
1451            return;
1452        }
1453
1454        if (!mLayoutEnabled) {
1455            discardLayoutInfo();
1456            removeAndRecycleAllViews(recycler);
1457            return;
1458        }
1459        mInLayout = true;
1460
1461        final boolean scrollToFocus = !isSmoothScrolling()
1462                && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED;
1463        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
1464            mFocusPosition = mFocusPosition + mFocusPositionOffset;
1465            mFocusPositionOffset = 0;
1466        }
1467        saveContext(recycler, state);
1468        // Track the old focus view so we can adjust our system scroll position
1469        // so that any scroll animations happening now will remain valid.
1470        // We must use same delta in Pre Layout (if prelayout exists) and second layout.
1471        // So we cache the deltas in PreLayout and use it in second layout.
1472        int delta = 0, deltaSecondary = 0;
1473        if (mFocusPosition != NO_POSITION && scrollToFocus) {
1474            // FIXME: we should get the remaining scroll animation offset from RecyclerView
1475            View focusView = findViewByPosition(mFocusPosition);
1476            if (focusView != null) {
1477                delta = mWindowAlignment.mainAxis().getSystemScrollPos(mScrollOffsetPrimary
1478                        + getViewCenter(focusView), false, false) - mScrollOffsetPrimary;
1479                deltaSecondary = mWindowAlignment.secondAxis().getSystemScrollPos(
1480                        mScrollOffsetSecondary + getViewCenterSecondary(focusView),
1481                        false, false) - mScrollOffsetSecondary;
1482            }
1483        }
1484
1485        final boolean hasDoneFirstLayout = hasDoneFirstLayout();
1486        int savedFocusPos = mFocusPosition;
1487        boolean fastRelayout = false;
1488        if (!mState.didStructureChange() && !mForceFullLayout && hasDoneFirstLayout) {
1489            fastRelayout = true;
1490            fastRelayout(scrollToFocus);
1491        } else {
1492            boolean hadFocus = mBaseGridView.hasFocus();
1493
1494            mFocusPosition = init(mFocusPosition);
1495            if (mFocusPosition != savedFocusPos) {
1496                if (DEBUG) Log.v(getTag(), "savedFocusPos " + savedFocusPos +
1497                        " mFocusPosition " + mFocusPosition);
1498            }
1499
1500            mWindowAlignment.mainAxis().invalidateScrollMin();
1501            mWindowAlignment.mainAxis().invalidateScrollMax();
1502            // depending on result of init(), either recreating everything
1503            // or try to reuse the row start positions near mFocusPosition
1504            if (mGrid.getSize() == 0) {
1505                // this is a fresh creating all items, starting from
1506                // mFocusPosition with a estimated row index.
1507                mGrid.setStart(mFocusPosition, StaggeredGrid.START_DEFAULT);
1508
1509                // Can't track the old focus view
1510                delta = deltaSecondary = 0;
1511
1512            } else {
1513                // mGrid remembers Locations for the column that
1514                // contains mFocusePosition and also mRows remembers start
1515                // positions of each row.
1516                // Manually re-create child views for that column
1517                int firstIndex = mGrid.getFirstIndex();
1518                int lastIndex = mGrid.getLastIndex();
1519                for (int i = firstIndex; i <= lastIndex; i++) {
1520                    mGridProvider.createItem(i, mGrid.getLocation(i).row, true);
1521                }
1522            }
1523
1524            // add visible views at end until reach the end of window
1525            appendVisibleItems();
1526            // add visible views at front until reach the start of window
1527            prependVisibleItems();
1528            // multiple rounds: scrollToView of first round may drag first/last child into
1529            // "visible window" and we update scrollMin/scrollMax then run second scrollToView
1530            int oldFirstVisible;
1531            int oldLastVisible;
1532            do {
1533                updateScrollMin();
1534                updateScrollMax();
1535                oldFirstVisible = mFirstVisiblePos;
1536                oldLastVisible = mLastVisiblePos;
1537                View focusView = findViewByPosition(mFocusPosition);
1538                // we need force to initialize the child view's position
1539                scrollToView(focusView, false);
1540                if (focusView != null && hadFocus) {
1541                    focusView.requestFocus();
1542                }
1543                appendVisibleItems();
1544                prependVisibleItems();
1545                removeInvisibleViewsAtFront();
1546                removeInvisibleViewsAtEnd();
1547            } while (mFirstVisiblePos != oldFirstVisible || mLastVisiblePos != oldLastVisible);
1548        }
1549        mForceFullLayout = false;
1550
1551        if (scrollToFocus) {
1552            scrollDirectionPrimary(-delta);
1553            scrollDirectionSecondary(-deltaSecondary);
1554        }
1555        appendVisibleItems();
1556        prependVisibleItems();
1557        removeInvisibleViewsAtFront();
1558        removeInvisibleViewsAtEnd();
1559
1560        if (DEBUG) {
1561            StringWriter sw = new StringWriter();
1562            PrintWriter pw = new PrintWriter(sw);
1563            mGrid.debugPrint(pw);
1564            Log.d(getTag(), sw.toString());
1565        }
1566
1567        if (mRowSecondarySizeRefresh) {
1568            mRowSecondarySizeRefresh = false;
1569        } else {
1570            updateRowSecondarySizeRefresh();
1571        }
1572
1573        if (fastRelayout && mFocusPosition != savedFocusPos) {
1574            dispatchChildSelected();
1575        }
1576        mInLayout = false;
1577        leaveContext();
1578        if (DEBUG) Log.v(getTag(), "layoutChildren end");
1579    }
1580
1581    private void offsetChildrenSecondary(int increment) {
1582        final int childCount = getChildCount();
1583        if (mOrientation == HORIZONTAL) {
1584            for (int i = 0; i < childCount; i++) {
1585                getChildAt(i).offsetTopAndBottom(increment);
1586            }
1587        } else {
1588            for (int i = 0; i < childCount; i++) {
1589                getChildAt(i).offsetLeftAndRight(increment);
1590            }
1591        }
1592    }
1593
1594    private void offsetChildrenPrimary(int increment) {
1595        final int childCount = getChildCount();
1596        if (mOrientation == VERTICAL) {
1597            for (int i = 0; i < childCount; i++) {
1598                getChildAt(i).offsetTopAndBottom(increment);
1599            }
1600        } else {
1601            for (int i = 0; i < childCount; i++) {
1602                getChildAt(i).offsetLeftAndRight(increment);
1603            }
1604        }
1605    }
1606
1607    @Override
1608    public int scrollHorizontallyBy(int dx, Recycler recycler, RecyclerView.State state) {
1609        if (DEBUG) Log.v(getTag(), "scrollHorizontallyBy " + dx);
1610        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1611            return 0;
1612        }
1613        saveContext(recycler, state);
1614        int result;
1615        if (mOrientation == HORIZONTAL) {
1616            result = scrollDirectionPrimary(dx);
1617        } else {
1618            result = scrollDirectionSecondary(dx);
1619        }
1620        leaveContext();
1621        return result;
1622    }
1623
1624    @Override
1625    public int scrollVerticallyBy(int dy, Recycler recycler, RecyclerView.State state) {
1626        if (DEBUG) Log.v(getTag(), "scrollVerticallyBy " + dy);
1627        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1628            return 0;
1629        }
1630        saveContext(recycler, state);
1631        int result;
1632        if (mOrientation == VERTICAL) {
1633            result = scrollDirectionPrimary(dy);
1634        } else {
1635            result = scrollDirectionSecondary(dy);
1636        }
1637        leaveContext();
1638        return result;
1639    }
1640
1641    // scroll in main direction may add/prune views
1642    private int scrollDirectionPrimary(int da) {
1643        if (da > 0) {
1644            if (!mWindowAlignment.mainAxis().isMaxUnknown()) {
1645                int maxScroll = mWindowAlignment.mainAxis().getMaxScroll();
1646                if (mScrollOffsetPrimary + da > maxScroll) {
1647                    da = maxScroll - mScrollOffsetPrimary;
1648                }
1649            }
1650        } else if (da < 0) {
1651            if (!mWindowAlignment.mainAxis().isMinUnknown()) {
1652                int minScroll = mWindowAlignment.mainAxis().getMinScroll();
1653                if (mScrollOffsetPrimary + da < minScroll) {
1654                    da = minScroll - mScrollOffsetPrimary;
1655                }
1656            }
1657        }
1658        if (da == 0) {
1659            return 0;
1660        }
1661        offsetChildrenPrimary(-da);
1662        mScrollOffsetPrimary += da;
1663        if (mInLayout) {
1664            return da;
1665        }
1666
1667        int childCount = getChildCount();
1668        boolean updated;
1669
1670        if (da > 0) {
1671            appendVisibleItems();
1672        } else if (da < 0) {
1673            prependVisibleItems();
1674        }
1675        updated = getChildCount() > childCount;
1676        childCount = getChildCount();
1677
1678        if (da > 0) {
1679            removeInvisibleViewsAtFront();
1680        } else if (da < 0) {
1681            removeInvisibleViewsAtEnd();
1682        }
1683        updated |= getChildCount() < childCount;
1684
1685        if (updated) {
1686            updateRowSecondarySizeRefresh();
1687        }
1688
1689        mBaseGridView.invalidate();
1690        return da;
1691    }
1692
1693    // scroll in second direction will not add/prune views
1694    private int scrollDirectionSecondary(int dy) {
1695        if (dy == 0) {
1696            return 0;
1697        }
1698        offsetChildrenSecondary(-dy);
1699        mScrollOffsetSecondary += dy;
1700        mBaseGridView.invalidate();
1701        return dy;
1702    }
1703
1704    private void updateScrollMax() {
1705        if (mLastVisiblePos < 0) {
1706            return;
1707        }
1708        final boolean lastAvailable = mLastVisiblePos == mState.getItemCount() - 1;
1709        final boolean maxUnknown = mWindowAlignment.mainAxis().isMaxUnknown();
1710        if (!lastAvailable && maxUnknown) {
1711            return;
1712        }
1713        int maxEdge = Integer.MIN_VALUE;
1714        int rowIndex = -1;
1715        for (int i = 0; i < mRows.length; i++) {
1716            if (mRows[i].high > maxEdge) {
1717                maxEdge = mRows[i].high;
1718                rowIndex = i;
1719            }
1720        }
1721        int maxScroll = Integer.MAX_VALUE;
1722        for (int i = mLastVisiblePos; i >= mFirstVisiblePos; i--) {
1723            StaggeredGrid.Location location = mGrid.getLocation(i);
1724            if (location != null && location.row == rowIndex) {
1725                int savedMaxEdge = mWindowAlignment.mainAxis().getMaxEdge();
1726                mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1727                maxScroll = getPrimarySystemScrollPosition(findViewByPosition(i));
1728                mWindowAlignment.mainAxis().setMaxEdge(savedMaxEdge);
1729                break;
1730            }
1731        }
1732        if (lastAvailable) {
1733            mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1734            mWindowAlignment.mainAxis().setMaxScroll(maxScroll);
1735            if (DEBUG) Log.v(getTag(), "updating scroll maxEdge to " + maxEdge +
1736                    " scrollMax to " + maxScroll);
1737        } else {
1738            // the maxScroll for currently last visible item is larger,
1739            // so we must invalidate the max scroll value.
1740            if (maxScroll > mWindowAlignment.mainAxis().getMaxScroll()) {
1741                mWindowAlignment.mainAxis().invalidateScrollMax();
1742                if (DEBUG) Log.v(getTag(), "Invalidate scrollMax since it should be "
1743                        + "greater than " + maxScroll);
1744            }
1745        }
1746    }
1747
1748    private void updateScrollMin() {
1749        if (mFirstVisiblePos < 0) {
1750            return;
1751        }
1752        final boolean firstAvailable = mFirstVisiblePos == 0;
1753        final boolean minUnknown = mWindowAlignment.mainAxis().isMinUnknown();
1754        if (!firstAvailable && minUnknown) {
1755            return;
1756        }
1757        int minEdge = Integer.MAX_VALUE;
1758        int rowIndex = -1;
1759        for (int i = 0; i < mRows.length; i++) {
1760            if (mRows[i].low < minEdge) {
1761                minEdge = mRows[i].low;
1762                rowIndex = i;
1763            }
1764        }
1765        int minScroll = Integer.MIN_VALUE;
1766        for (int i = mFirstVisiblePos; i <= mLastVisiblePos; i++) {
1767            StaggeredGrid.Location location = mGrid.getLocation(i);
1768            if (location != null && location.row == rowIndex) {
1769                int savedMinEdge = mWindowAlignment.mainAxis().getMinEdge();
1770                mWindowAlignment.mainAxis().setMinEdge(minEdge);
1771                minScroll = getPrimarySystemScrollPosition(findViewByPosition(i));
1772                mWindowAlignment.mainAxis().setMinEdge(savedMinEdge);
1773                break;
1774            }
1775        }
1776        if (firstAvailable) {
1777            mWindowAlignment.mainAxis().setMinEdge(minEdge);
1778            mWindowAlignment.mainAxis().setMinScroll(minScroll);
1779            if (DEBUG) Log.v(getTag(), "updating scroll minEdge to " + minEdge +
1780                    " scrollMin to " + minScroll);
1781        } else {
1782            // the minScroll for currently first visible item is smaller,
1783            // so we must invalidate the min scroll value.
1784            if (minScroll < mWindowAlignment.mainAxis().getMinScroll()) {
1785                mWindowAlignment.mainAxis().invalidateScrollMin();
1786                if (DEBUG) Log.v(getTag(), "Invalidate scrollMin, since it should be "
1787                        + "less than " + minScroll);
1788            }
1789        }
1790    }
1791
1792    private void updateScrollSecondAxis() {
1793        mWindowAlignment.secondAxis().setMinEdge(0);
1794        mWindowAlignment.secondAxis().setMaxEdge(getSizeSecondary());
1795    }
1796
1797    private void initScrollController() {
1798        // mScrollOffsetPrimary and mScrollOffsetSecondary includes the padding.
1799        // e.g. when topPadding is 16 for horizontal grid view,  the initial
1800        // mScrollOffsetSecondary is -16.  fastLayout() put views based on offsets(not padding),
1801        // when padding changes to 20,  we also need update mScrollOffsetSecondary to -20 before
1802        // fastLayout() is performed
1803        int paddingPrimaryDiff, paddingSecondaryDiff;
1804        if (mOrientation == HORIZONTAL) {
1805            paddingPrimaryDiff = getPaddingLeft() - mWindowAlignment.horizontal.getPaddingLow();
1806            paddingSecondaryDiff = getPaddingTop() - mWindowAlignment.vertical.getPaddingLow();
1807        } else {
1808            paddingPrimaryDiff = getPaddingTop() - mWindowAlignment.vertical.getPaddingLow();
1809            paddingSecondaryDiff = getPaddingLeft() - mWindowAlignment.horizontal.getPaddingLow();
1810        }
1811        mScrollOffsetPrimary -= paddingPrimaryDiff;
1812        mScrollOffsetSecondary -= paddingSecondaryDiff;
1813
1814        mWindowAlignment.horizontal.setSize(getWidth());
1815        mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight());
1816        mWindowAlignment.vertical.setSize(getHeight());
1817        mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom());
1818        mSizePrimary = mWindowAlignment.mainAxis().getSize();
1819
1820        if (DEBUG) {
1821            Log.v(getTag(), "initScrollController mSizePrimary " + mSizePrimary
1822                    + " mWindowAlignment " + mWindowAlignment);
1823        }
1824    }
1825
1826    public void setSelection(RecyclerView parent, int position) {
1827        setSelection(parent, position, false);
1828    }
1829
1830    public void setSelectionSmooth(RecyclerView parent, int position) {
1831        setSelection(parent, position, true);
1832    }
1833
1834    public int getSelection() {
1835        return mFocusPosition;
1836    }
1837
1838    public void setSelection(RecyclerView parent, int position, boolean smooth) {
1839        if (mFocusPosition == position) {
1840            return;
1841        }
1842        View view = findViewByPosition(position);
1843        if (view != null) {
1844            mInSelection = true;
1845            scrollToView(view, smooth);
1846            mInSelection = false;
1847        } else {
1848            mFocusPosition = position;
1849            mFocusPositionOffset = 0;
1850            if (!mLayoutEnabled) {
1851                return;
1852            }
1853            if (smooth) {
1854                if (!hasDoneFirstLayout()) {
1855                    Log.w(getTag(), "setSelectionSmooth should " +
1856                            "not be called before first layout pass");
1857                    return;
1858                }
1859                LinearSmoothScroller linearSmoothScroller =
1860                        new LinearSmoothScroller(parent.getContext()) {
1861                    @Override
1862                    public PointF computeScrollVectorForPosition(int targetPosition) {
1863                        if (getChildCount() == 0) {
1864                            return null;
1865                        }
1866                        final int firstChildPos = getPosition(getChildAt(0));
1867                        final int direction = targetPosition < firstChildPos ? -1 : 1;
1868                        if (mOrientation == HORIZONTAL) {
1869                            return new PointF(direction, 0);
1870                        } else {
1871                            return new PointF(0, direction);
1872                        }
1873                    }
1874                    @Override
1875                    protected void onTargetFound(View targetView,
1876                            RecyclerView.State state, Action action) {
1877                        if (hasFocus()) {
1878                            targetView.requestFocus();
1879                        }
1880                        dispatchChildSelected();
1881                        if (getScrollPosition(targetView, mTempDeltas)) {
1882                            int dx, dy;
1883                            if (mOrientation == HORIZONTAL) {
1884                                dx = mTempDeltas[0];
1885                                dy = mTempDeltas[1];
1886                            } else {
1887                                dx = mTempDeltas[1];
1888                                dy = mTempDeltas[0];
1889                            }
1890                            final int distance = (int) Math.sqrt(dx * dx + dy * dy);
1891                            final int time = calculateTimeForDeceleration(distance);
1892                            action.update(dx, dy, time, mDecelerateInterpolator);
1893                        }
1894                    }
1895                };
1896                linearSmoothScroller.setTargetPosition(position);
1897                startSmoothScroll(linearSmoothScroller);
1898            } else {
1899                mForceFullLayout = true;
1900                parent.requestLayout();
1901            }
1902        }
1903    }
1904
1905    @Override
1906    public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
1907        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE
1908                && getChildAt(mFocusPosition) != null) {
1909            int pos = mFocusPosition + mFocusPositionOffset;
1910            if (positionStart <= pos) {
1911                mFocusPositionOffset += itemCount;
1912            }
1913        }
1914        mChildrenStates.clear();
1915    }
1916
1917    @Override
1918    public void onItemsChanged(RecyclerView recyclerView) {
1919        mFocusPositionOffset = 0;
1920        mChildrenStates.clear();
1921    }
1922
1923    @Override
1924    public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) {
1925        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE
1926                && getChildAt(mFocusPosition) != null) {
1927            int pos = mFocusPosition + mFocusPositionOffset;
1928            if (positionStart <= pos) {
1929                if (positionStart + itemCount > pos) {
1930                    // stop updating offset after the focus item was removed
1931                    mFocusPositionOffset = Integer.MIN_VALUE;
1932                } else {
1933                    mFocusPositionOffset -= itemCount;
1934                }
1935            }
1936        }
1937        mChildrenStates.clear();
1938    }
1939
1940    @Override
1941    public void onItemsMoved(RecyclerView recyclerView, int fromPosition, int toPosition,
1942            int itemCount) {
1943        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE
1944                && getChildAt(mFocusPosition) != null) {
1945            int pos = mFocusPosition + mFocusPositionOffset;
1946            if (fromPosition <= pos && pos < fromPosition + itemCount) {
1947                // moved items include focused position
1948                mFocusPositionOffset += toPosition - fromPosition;
1949            } else if (fromPosition < pos && toPosition > pos - itemCount) {
1950                // move items before focus position to after focused position
1951                mFocusPositionOffset -= itemCount;
1952            } else if (fromPosition > pos && toPosition < pos) {
1953                // move items after focus position to before focused position
1954                mFocusPositionOffset += itemCount;
1955            }
1956        }
1957        mChildrenStates.clear();
1958    }
1959
1960    @Override
1961    public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount) {
1962        for (int i = positionStart, end = positionStart + itemCount; i < end; i++) {
1963            mChildrenStates.remove(i);
1964        }
1965    }
1966
1967    @Override
1968    public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) {
1969        if (mFocusSearchDisabled) {
1970            return true;
1971        }
1972        if (!mInLayout && !mInSelection) {
1973            scrollToView(child, true);
1974        }
1975        return true;
1976    }
1977
1978    @Override
1979    public boolean requestChildRectangleOnScreen(RecyclerView parent, View view, Rect rect,
1980            boolean immediate) {
1981        if (DEBUG) Log.v(getTag(), "requestChildRectangleOnScreen " + view + " " + rect);
1982        return false;
1983    }
1984
1985    int getScrollOffsetX() {
1986        return mOrientation == HORIZONTAL ? mScrollOffsetPrimary : mScrollOffsetSecondary;
1987    }
1988
1989    int getScrollOffsetY() {
1990        return mOrientation == HORIZONTAL ? mScrollOffsetSecondary : mScrollOffsetPrimary;
1991    }
1992
1993    public void getViewSelectedOffsets(View view, int[] offsets) {
1994        if (mOrientation == HORIZONTAL) {
1995            offsets[0] = getPrimarySystemScrollPosition(view) - mScrollOffsetPrimary;
1996            offsets[1] = getSecondarySystemScrollPosition(view) - mScrollOffsetSecondary;
1997        } else {
1998            offsets[1] = getPrimarySystemScrollPosition(view) - mScrollOffsetPrimary;
1999            offsets[0] = getSecondarySystemScrollPosition(view) - mScrollOffsetSecondary;
2000        }
2001    }
2002
2003    private int getPrimarySystemScrollPosition(View view) {
2004        int viewCenterPrimary = mScrollOffsetPrimary + getViewCenter(view);
2005        int pos = getPositionByView(view);
2006        StaggeredGrid.Location location = mGrid.getLocation(pos);
2007        final int row = location.row;
2008        boolean isFirst = mFirstVisiblePos == 0;
2009        // TODO: change to use State object in onRequestChildFocus()
2010        boolean isLast = mLastVisiblePos == (mState == null ?
2011                getItemCount() : mState.getItemCount()) - 1;
2012        if (isFirst || isLast) {
2013            for (int i = getChildCount() - 1; i >= 0; i--) {
2014                int position = getPositionByIndex(i);
2015                StaggeredGrid.Location loc = mGrid.getLocation(position);
2016                if (loc != null && loc.row == row) {
2017                    if (position < pos) {
2018                        isFirst = false;
2019                    } else if (position > pos) {
2020                        isLast = false;
2021                    }
2022                }
2023            }
2024        }
2025        return mWindowAlignment.mainAxis().getSystemScrollPos(viewCenterPrimary, isFirst, isLast);
2026    }
2027
2028    private int getSecondarySystemScrollPosition(View view) {
2029        int viewCenterSecondary = mScrollOffsetSecondary + getViewCenterSecondary(view);
2030        int pos = getPositionByView(view);
2031        StaggeredGrid.Location location = mGrid.getLocation(pos);
2032        final int row = location.row;
2033        boolean isFirst = row == 0;
2034        boolean isLast = row == mGrid.getNumRows() - 1;
2035        return mWindowAlignment.secondAxis().getSystemScrollPos(viewCenterSecondary,
2036                isFirst, isLast);
2037    }
2038
2039    /**
2040     * Scroll to a given child view and change mFocusPosition.
2041     */
2042    private void scrollToView(View view, boolean smooth) {
2043        int newFocusPosition = getPositionByView(view);
2044        if (newFocusPosition != mFocusPosition) {
2045            mFocusPosition = newFocusPosition;
2046            mFocusPositionOffset = 0;
2047            if (!mInLayout) {
2048                dispatchChildSelected();
2049            }
2050        }
2051        if (mBaseGridView.isChildrenDrawingOrderEnabledInternal()) {
2052            mBaseGridView.invalidate();
2053        }
2054        if (view == null) {
2055            return;
2056        }
2057        if (!view.hasFocus() && mBaseGridView.hasFocus()) {
2058            // transfer focus to the child if it does not have focus yet (e.g. triggered
2059            // by setSelection())
2060            view.requestFocus();
2061        }
2062        if (!mScrollEnabled) {
2063            return;
2064        }
2065        if (getScrollPosition(view, mTempDeltas)) {
2066            scrollGrid(mTempDeltas[0], mTempDeltas[1], smooth);
2067        }
2068    }
2069
2070    private boolean getScrollPosition(View view, int[] deltas) {
2071        switch (mFocusScrollStrategy) {
2072        case BaseGridView.FOCUS_SCROLL_ALIGNED:
2073        default:
2074            return getAlignedPosition(view, deltas);
2075        case BaseGridView.FOCUS_SCROLL_ITEM:
2076        case BaseGridView.FOCUS_SCROLL_PAGE:
2077            return getNoneAlignedPosition(view, deltas);
2078        }
2079    }
2080
2081    private boolean getNoneAlignedPosition(View view, int[] deltas) {
2082        int pos = getPositionByView(view);
2083        int viewMin = getViewMin(view);
2084        int viewMax = getViewMax(view);
2085        // we either align "firstView" to left/top padding edge
2086        // or align "lastView" to right/bottom padding edge
2087        View firstView = null;
2088        View lastView = null;
2089        int paddingLow = mWindowAlignment.mainAxis().getPaddingLow();
2090        int clientSize = mWindowAlignment.mainAxis().getClientSize();
2091        final int row = mGrid.getLocation(pos).row;
2092        if (viewMin < paddingLow) {
2093            // view enters low padding area:
2094            firstView = view;
2095            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
2096                // scroll one "page" left/top,
2097                // align first visible item of the "page" at the low padding edge.
2098                while (!prependOneVisibleItem()) {
2099                    List<Integer> positions =
2100                            mGrid.getItemPositionsInRows(mFirstVisiblePos, pos)[row];
2101                    firstView = findViewByPosition(positions.get(0));
2102                    if (viewMax - getViewMin(firstView) > clientSize) {
2103                        if (positions.size() > 1) {
2104                            firstView = findViewByPosition(positions.get(1));
2105                        }
2106                        break;
2107                    }
2108                }
2109            }
2110        } else if (viewMax > clientSize + paddingLow) {
2111            // view enters high padding area:
2112            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
2113                // scroll whole one page right/bottom, align view at the low padding edge.
2114                firstView = view;
2115                do {
2116                    List<Integer> positions =
2117                            mGrid.getItemPositionsInRows(pos, mLastVisiblePos)[row];
2118                    lastView = findViewByPosition(positions.get(positions.size() - 1));
2119                    if (getViewMax(lastView) - viewMin > clientSize) {
2120                        lastView = null;
2121                        break;
2122                    }
2123                } while (!appendOneVisibleItem());
2124                if (lastView != null) {
2125                    // however if we reached end,  we should align last view.
2126                    firstView = null;
2127                }
2128            } else {
2129                lastView = view;
2130            }
2131        }
2132        int scrollPrimary = 0;
2133        int scrollSecondary = 0;
2134        if (firstView != null) {
2135            scrollPrimary = getViewMin(firstView) - paddingLow;
2136        } else if (lastView != null) {
2137            scrollPrimary = getViewMax(lastView) - (paddingLow + clientSize);
2138        }
2139        View secondaryAlignedView;
2140        if (firstView != null) {
2141            secondaryAlignedView = firstView;
2142        } else if (lastView != null) {
2143            secondaryAlignedView = lastView;
2144        } else {
2145            secondaryAlignedView = view;
2146        }
2147        scrollSecondary = getSecondarySystemScrollPosition(secondaryAlignedView);
2148        scrollSecondary -= mScrollOffsetSecondary;
2149        if (scrollPrimary != 0 || scrollSecondary != 0) {
2150            deltas[0] = scrollPrimary;
2151            deltas[1] = scrollSecondary;
2152            return true;
2153        }
2154        return false;
2155    }
2156
2157    private boolean getAlignedPosition(View view, int[] deltas) {
2158        int scrollPrimary = getPrimarySystemScrollPosition(view);
2159        int scrollSecondary = getSecondarySystemScrollPosition(view);
2160        if (DEBUG) {
2161            Log.v(getTag(), "getAlignedPosition " + scrollPrimary + " " + scrollSecondary
2162                    +" " + mWindowAlignment);
2163        }
2164        scrollPrimary -= mScrollOffsetPrimary;
2165        scrollSecondary -= mScrollOffsetSecondary;
2166        if (scrollPrimary != 0 || scrollSecondary != 0) {
2167            deltas[0] = scrollPrimary;
2168            deltas[1] = scrollSecondary;
2169            return true;
2170        }
2171        return false;
2172    }
2173
2174    private void scrollGrid(int scrollPrimary, int scrollSecondary, boolean smooth) {
2175        if (mInLayout) {
2176            scrollDirectionPrimary(scrollPrimary);
2177            scrollDirectionSecondary(scrollSecondary);
2178        } else {
2179            int scrollX;
2180            int scrollY;
2181            if (mOrientation == HORIZONTAL) {
2182                scrollX = scrollPrimary;
2183                scrollY = scrollSecondary;
2184            } else {
2185                scrollX = scrollSecondary;
2186                scrollY = scrollPrimary;
2187            }
2188            if (smooth) {
2189                mBaseGridView.smoothScrollBy(scrollX, scrollY);
2190            } else {
2191                mBaseGridView.scrollBy(scrollX, scrollY);
2192            }
2193        }
2194    }
2195
2196    public void setPruneChild(boolean pruneChild) {
2197        if (mPruneChild != pruneChild) {
2198            mPruneChild = pruneChild;
2199            if (mPruneChild) {
2200                requestLayout();
2201            }
2202        }
2203    }
2204
2205    public boolean getPruneChild() {
2206        return mPruneChild;
2207    }
2208
2209    public void setScrollEnabled(boolean scrollEnabled) {
2210        if (mScrollEnabled != scrollEnabled) {
2211            mScrollEnabled = scrollEnabled;
2212            if (mScrollEnabled && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
2213                View focusView = findViewByPosition(mFocusPosition == NO_POSITION ? 0 :
2214                    mFocusPosition);
2215                if (focusView != null) {
2216                    scrollToView(focusView, true);
2217                }
2218            }
2219        }
2220    }
2221
2222    public boolean isScrollEnabled() {
2223        return mScrollEnabled;
2224    }
2225
2226    private int findImmediateChildIndex(View view) {
2227        while (view != null && view != mBaseGridView) {
2228            int index = mBaseGridView.indexOfChild(view);
2229            if (index >= 0) {
2230                return index;
2231            }
2232            view = (View) view.getParent();
2233        }
2234        return NO_POSITION;
2235    }
2236
2237    void setFocusSearchDisabled(boolean disabled) {
2238        mFocusSearchDisabled = disabled;
2239    }
2240
2241    boolean isFocusSearchDisabled() {
2242        return mFocusSearchDisabled;
2243    }
2244
2245    @Override
2246    public View onInterceptFocusSearch(View focused, int direction) {
2247        if (mFocusSearchDisabled) {
2248            return focused;
2249        }
2250        return null;
2251    }
2252
2253    boolean hasPreviousViewInSameRow(int pos) {
2254        if (mGrid == null || pos == NO_POSITION) {
2255            return false;
2256        }
2257        if (mFirstVisiblePos > 0) {
2258            return true;
2259        }
2260        final int focusedRow = mGrid.getLocation(pos).row;
2261        for (int i = getChildCount() - 1; i >= 0; i--) {
2262            int position = getPositionByIndex(i);
2263            StaggeredGrid.Location loc = mGrid.getLocation(position);
2264            if (loc != null && loc.row == focusedRow) {
2265                if (position < pos) {
2266                    return true;
2267                }
2268            }
2269        }
2270        return false;
2271    }
2272
2273    @Override
2274    public boolean onAddFocusables(RecyclerView recyclerView,
2275            ArrayList<View> views, int direction, int focusableMode) {
2276        if (mFocusSearchDisabled) {
2277            return true;
2278        }
2279        // If this viewgroup or one of its children currently has focus then we
2280        // consider our children for focus searching in main direction on the same row.
2281        // If this viewgroup has no focus and using focus align, we want the system
2282        // to ignore our children and pass focus to the viewgroup, which will pass
2283        // focus on to its children appropriately.
2284        // If this viewgroup has no focus and not using focus align, we want to
2285        // consider the child that does not overlap with padding area.
2286        if (recyclerView.hasFocus()) {
2287            final int movement = getMovement(direction);
2288            if (movement != PREV_ITEM && movement != NEXT_ITEM) {
2289                // Move on secondary direction uses default addFocusables().
2290                return false;
2291            }
2292            final View focused = recyclerView.findFocus();
2293            final int focusedPos = getPositionByIndex(findImmediateChildIndex(focused));
2294            // Add focusables of focused item.
2295            if (focusedPos != NO_POSITION) {
2296                findViewByPosition(focusedPos).addFocusables(views,  direction, focusableMode);
2297            }
2298            final int focusedRow = mGrid != null && focusedPos != NO_POSITION ?
2299                    mGrid.getLocation(focusedPos).row : NO_POSITION;
2300            // Add focusables of next neighbor of same row on the focus search direction.
2301            if (mGrid != null) {
2302                final int focusableCount = views.size();
2303                for (int i = 0, count = getChildCount(); i < count; i++) {
2304                    int index = movement == NEXT_ITEM ? i : count - 1 - i;
2305                    final View child = getChildAt(index);
2306                    if (child.getVisibility() != View.VISIBLE) {
2307                        continue;
2308                    }
2309                    int position = getPositionByIndex(index);
2310                    StaggeredGrid.Location loc = mGrid.getLocation(position);
2311                    if (focusedRow == NO_POSITION || (loc != null && loc.row == focusedRow)) {
2312                        if (focusedPos == NO_POSITION ||
2313                                (movement == NEXT_ITEM && position > focusedPos)
2314                                || (movement == PREV_ITEM && position < focusedPos)) {
2315                            child.addFocusables(views,  direction, focusableMode);
2316                            if (views.size() > focusableCount) {
2317                                break;
2318                            }
2319                        }
2320                    }
2321                }
2322            }
2323        } else {
2324            if (mFocusScrollStrategy != BaseGridView.FOCUS_SCROLL_ALIGNED) {
2325                // adding views not overlapping padding area to avoid scrolling in gaining focus
2326                int left = mWindowAlignment.mainAxis().getPaddingLow();
2327                int right = mWindowAlignment.mainAxis().getClientSize() + left;
2328                int focusableCount = views.size();
2329                for (int i = 0, count = getChildCount(); i < count; i++) {
2330                    View child = getChildAt(i);
2331                    if (child.getVisibility() == View.VISIBLE) {
2332                        if (getViewMin(child) >= left && getViewMax(child) <= right) {
2333                            child.addFocusables(views, direction, focusableMode);
2334                        }
2335                    }
2336                }
2337                // if we cannot find any, then just add all children.
2338                if (views.size() == focusableCount) {
2339                    for (int i = 0, count = getChildCount(); i < count; i++) {
2340                        View child = getChildAt(i);
2341                        if (child.getVisibility() == View.VISIBLE) {
2342                            child.addFocusables(views, direction, focusableMode);
2343                        }
2344                    }
2345                    if (views.size() != focusableCount) {
2346                        return true;
2347                    }
2348                } else {
2349                    return true;
2350                }
2351                // if still cannot find any, fall through and add itself
2352            }
2353            if (recyclerView.isFocusable()) {
2354                views.add(recyclerView);
2355            }
2356        }
2357        return true;
2358    }
2359
2360    @Override
2361    public View onFocusSearchFailed(View focused, int direction, Recycler recycler,
2362            RecyclerView.State state) {
2363        if (DEBUG) Log.v(getTag(), "onFocusSearchFailed direction " + direction);
2364
2365        View view = null;
2366        int movement = getMovement(direction);
2367        if (mNumRows == 1) {
2368            // for simple row, use LinearSmoothScroller to smooth animation.
2369            // It will stay at a fixed cap speed in continuous scroll.
2370            if (movement == NEXT_ITEM) {
2371                int newPos = mFocusPosition + mNumRows;
2372                if (newPos < getItemCount()) {
2373                    setSelectionSmooth(mBaseGridView, newPos);
2374                    view = focused;
2375                } else {
2376                    if (!mFocusOutEnd) {
2377                        view = focused;
2378                    }
2379                }
2380            } else if (movement == PREV_ITEM){
2381                int newPos = mFocusPosition - mNumRows;
2382                if (newPos >= 0) {
2383                    setSelectionSmooth(mBaseGridView, newPos);
2384                    view = focused;
2385                } else {
2386                    if (!mFocusOutFront) {
2387                        view = focused;
2388                    }
2389                }
2390            }
2391        } else if (mNumRows > 1) {
2392            // for possible staggered grid,  we need guarantee focus to same row/column.
2393            // TODO: we may also use LinearSmoothScroller.
2394            saveContext(recycler, state);
2395            final FocusFinder ff = FocusFinder.getInstance();
2396            if (movement == NEXT_ITEM) {
2397                while (view == null && !appendOneVisibleItem()) {
2398                    view = ff.findNextFocus(mBaseGridView, focused, direction);
2399                }
2400            } else if (movement == PREV_ITEM){
2401                while (view == null && !prependOneVisibleItem()) {
2402                    view = ff.findNextFocus(mBaseGridView, focused, direction);
2403                }
2404            }
2405            if (view == null) {
2406                // returning the same view to prevent focus lost when scrolling past the end of the list
2407                if (movement == PREV_ITEM) {
2408                    view = mFocusOutFront ? null : focused;
2409                } else if (movement == NEXT_ITEM){
2410                    view = mFocusOutEnd ? null : focused;
2411                }
2412            }
2413            leaveContext();
2414        }
2415        if (DEBUG) Log.v(getTag(), "returning view " + view);
2416        return view;
2417    }
2418
2419    boolean gridOnRequestFocusInDescendants(RecyclerView recyclerView, int direction,
2420            Rect previouslyFocusedRect) {
2421        switch (mFocusScrollStrategy) {
2422        case BaseGridView.FOCUS_SCROLL_ALIGNED:
2423        default:
2424            return gridOnRequestFocusInDescendantsAligned(recyclerView,
2425                    direction, previouslyFocusedRect);
2426        case BaseGridView.FOCUS_SCROLL_PAGE:
2427        case BaseGridView.FOCUS_SCROLL_ITEM:
2428            return gridOnRequestFocusInDescendantsUnaligned(recyclerView,
2429                    direction, previouslyFocusedRect);
2430        }
2431    }
2432
2433    private boolean gridOnRequestFocusInDescendantsAligned(RecyclerView recyclerView,
2434            int direction, Rect previouslyFocusedRect) {
2435        View view = findViewByPosition(mFocusPosition);
2436        if (view != null) {
2437            boolean result = view.requestFocus(direction, previouslyFocusedRect);
2438            if (!result && DEBUG) {
2439                Log.w(getTag(), "failed to request focus on " + view);
2440            }
2441            return result;
2442        }
2443        return false;
2444    }
2445
2446    private boolean gridOnRequestFocusInDescendantsUnaligned(RecyclerView recyclerView,
2447            int direction, Rect previouslyFocusedRect) {
2448        // focus to view not overlapping padding area to avoid scrolling in gaining focus
2449        int index;
2450        int increment;
2451        int end;
2452        int count = getChildCount();
2453        if ((direction & View.FOCUS_FORWARD) != 0) {
2454            index = 0;
2455            increment = 1;
2456            end = count;
2457        } else {
2458            index = count - 1;
2459            increment = -1;
2460            end = -1;
2461        }
2462        int left = mWindowAlignment.mainAxis().getPaddingLow();
2463        int right = mWindowAlignment.mainAxis().getClientSize() + left;
2464        for (int i = index; i != end; i += increment) {
2465            View child = getChildAt(i);
2466            if (child.getVisibility() == View.VISIBLE) {
2467                if (getViewMin(child) >= left && getViewMax(child) <= right) {
2468                    if (child.requestFocus(direction, previouslyFocusedRect)) {
2469                        return true;
2470                    }
2471                }
2472            }
2473        }
2474        return false;
2475    }
2476
2477    private final static int PREV_ITEM = 0;
2478    private final static int NEXT_ITEM = 1;
2479    private final static int PREV_ROW = 2;
2480    private final static int NEXT_ROW = 3;
2481
2482    private int getMovement(int direction) {
2483        int movement = View.FOCUS_LEFT;
2484
2485        if (mOrientation == HORIZONTAL) {
2486            switch(direction) {
2487                case View.FOCUS_LEFT:
2488                    movement = PREV_ITEM;
2489                    break;
2490                case View.FOCUS_RIGHT:
2491                    movement = NEXT_ITEM;
2492                    break;
2493                case View.FOCUS_UP:
2494                    movement = PREV_ROW;
2495                    break;
2496                case View.FOCUS_DOWN:
2497                    movement = NEXT_ROW;
2498                    break;
2499            }
2500         } else if (mOrientation == VERTICAL) {
2501             switch(direction) {
2502                 case View.FOCUS_LEFT:
2503                     movement = PREV_ROW;
2504                     break;
2505                 case View.FOCUS_RIGHT:
2506                     movement = NEXT_ROW;
2507                     break;
2508                 case View.FOCUS_UP:
2509                     movement = PREV_ITEM;
2510                     break;
2511                 case View.FOCUS_DOWN:
2512                     movement = NEXT_ITEM;
2513                     break;
2514             }
2515         }
2516
2517        return movement;
2518    }
2519
2520    int getChildDrawingOrder(RecyclerView recyclerView, int childCount, int i) {
2521        View view = findViewByPosition(mFocusPosition);
2522        if (view == null) {
2523            return i;
2524        }
2525        int focusIndex = recyclerView.indexOfChild(view);
2526        // supposely 0 1 2 3 4 5 6 7 8 9, 4 is the center item
2527        // drawing order is 0 1 2 3 9 8 7 6 5 4
2528        if (i < focusIndex) {
2529            return i;
2530        } else if (i < childCount - 1) {
2531            return focusIndex + childCount - 1 - i;
2532        } else {
2533            return focusIndex;
2534        }
2535    }
2536
2537    @Override
2538    public void onAdapterChanged(RecyclerView.Adapter oldAdapter,
2539            RecyclerView.Adapter newAdapter) {
2540        discardLayoutInfo();
2541        mFocusPosition = NO_POSITION;
2542        mFocusPositionOffset = 0;
2543        mChildrenStates.clear();
2544        super.onAdapterChanged(oldAdapter, newAdapter);
2545    }
2546
2547    private void discardLayoutInfo() {
2548        mGrid = null;
2549        mRows = null;
2550        mRowSizeSecondary = null;
2551        mFirstVisiblePos = -1;
2552        mLastVisiblePos = -1;
2553        mRowSecondarySizeRefresh = false;
2554    }
2555
2556    public void setLayoutEnabled(boolean layoutEnabled) {
2557        if (mLayoutEnabled != layoutEnabled) {
2558            mLayoutEnabled = layoutEnabled;
2559            requestLayout();
2560        }
2561    }
2562
2563    final static class SavedState implements Parcelable {
2564
2565        int index; // index inside adapter of the current view
2566        Bundle childStates = Bundle.EMPTY;
2567
2568        @Override
2569        public void writeToParcel(Parcel out, int flags) {
2570            out.writeInt(index);
2571            out.writeBundle(childStates);
2572        }
2573
2574        @SuppressWarnings("hiding")
2575        public static final Parcelable.Creator<SavedState> CREATOR =
2576                new Parcelable.Creator<SavedState>() {
2577                    @Override
2578                    public SavedState createFromParcel(Parcel in) {
2579                        return new SavedState(in);
2580                    }
2581
2582                    @Override
2583                    public SavedState[] newArray(int size) {
2584                        return new SavedState[size];
2585                    }
2586                };
2587
2588        @Override
2589        public int describeContents() {
2590            return 0;
2591        }
2592
2593        SavedState(Parcel in) {
2594            index = in.readInt();
2595            childStates = in.readBundle(GridLayoutManager.class.getClassLoader());
2596        }
2597
2598        SavedState() {
2599        }
2600    }
2601
2602    @Override
2603    public Parcelable onSaveInstanceState() {
2604        SavedState ss = new SavedState();
2605        for (int i = 0, count = getChildCount(); i < count; i++) {
2606            View view = getChildAt(i);
2607            int position = getPositionByView(view);
2608            if (position != NO_POSITION) {
2609                mChildrenStates.saveOnScreenView(view, position);
2610            }
2611        }
2612        ss.index = getSelection();
2613        ss.childStates = mChildrenStates.saveAsBundle();
2614        return ss;
2615    }
2616
2617    @Override
2618    public void onRestoreInstanceState(Parcelable state) {
2619        if (!(state instanceof SavedState)) {
2620            return;
2621        }
2622        SavedState loadingState = (SavedState)state;
2623        mFocusPosition = loadingState.index;
2624        mFocusPositionOffset = 0;
2625        mChildrenStates.loadFromBundle(loadingState.childStates);
2626        mForceFullLayout = true;
2627        requestLayout();
2628    }
2629}
2630