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