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