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