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