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