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