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