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