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