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