GridLayoutManager.java revision b300ce0dfc3ad41fd6fef25833dfe4b14d5261d2
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            mWindowAlignment.mainAxis().invalidateScrollMin();
1503            mWindowAlignment.mainAxis().invalidateScrollMax();
1504            // depending on result of init(), either recreating everything
1505            // or try to reuse the row start positions near mFocusPosition
1506            if (mGrid.getSize() == 0) {
1507                // this is a fresh creating all items, starting from
1508                // mFocusPosition with a estimated row index.
1509                mGrid.setStart(newFocusPosition, StaggeredGrid.START_DEFAULT);
1510
1511                // Can't track the old focus view
1512                delta = deltaSecondary = 0;
1513
1514            } else {
1515                // mGrid remembers Locations for the column that
1516                // contains mFocusePosition and also mRows remembers start
1517                // positions of each row.
1518                // Manually re-create child views for that column
1519                int firstIndex = mGrid.getFirstIndex();
1520                int lastIndex = mGrid.getLastIndex();
1521                for (int i = firstIndex; i <= lastIndex; i++) {
1522                    mGridProvider.createItem(i, mGrid.getLocation(i).row, true);
1523                }
1524            }
1525            // add visible views at end until reach the end of window
1526            appendVisibleItems();
1527            // add visible views at front until reach the start of window
1528            prependVisibleItems();
1529            // multiple rounds: scrollToView of first round may drag first/last child into
1530            // "visible window" and we update scrollMin/scrollMax then run second scrollToView
1531            int oldFirstVisible;
1532            int oldLastVisible;
1533            do {
1534                updateScrollMin();
1535                updateScrollMax();
1536                oldFirstVisible = mFirstVisiblePos;
1537                oldLastVisible = mLastVisiblePos;
1538                View focusView = findViewByPosition(newFocusPosition);
1539                // we need force to initialize the child view's position
1540                scrollToView(focusView, false);
1541                if (focusView != null && hadFocus) {
1542                    focusView.requestFocus();
1543                }
1544                appendVisibleItems();
1545                prependVisibleItems();
1546                removeInvisibleViewsAtFront();
1547                removeInvisibleViewsAtEnd();
1548            } while (mFirstVisiblePos != oldFirstVisible || mLastVisiblePos != oldLastVisible);
1549        }
1550        mForceFullLayout = false;
1551
1552        if (scrollToFocus) {
1553            scrollDirectionPrimary(-delta);
1554            scrollDirectionSecondary(-deltaSecondary);
1555        }
1556        appendVisibleItems();
1557        prependVisibleItems();
1558        removeInvisibleViewsAtFront();
1559        removeInvisibleViewsAtEnd();
1560
1561        if (DEBUG) {
1562            StringWriter sw = new StringWriter();
1563            PrintWriter pw = new PrintWriter(sw);
1564            mGrid.debugPrint(pw);
1565            Log.d(getTag(), sw.toString());
1566        }
1567
1568        if (mRowSecondarySizeRefresh) {
1569            mRowSecondarySizeRefresh = false;
1570        } else {
1571            updateRowSecondarySizeRefresh();
1572        }
1573
1574        if (!fastRelayout || mFocusPosition != savedFocusPos) {
1575            dispatchChildSelected();
1576        }
1577        mInLayout = false;
1578        leaveContext();
1579        if (DEBUG) Log.v(getTag(), "layoutChildren end");
1580    }
1581
1582    private void offsetChildrenSecondary(int increment) {
1583        final int childCount = getChildCount();
1584        if (mOrientation == HORIZONTAL) {
1585            for (int i = 0; i < childCount; i++) {
1586                getChildAt(i).offsetTopAndBottom(increment);
1587            }
1588        } else {
1589            for (int i = 0; i < childCount; i++) {
1590                getChildAt(i).offsetLeftAndRight(increment);
1591            }
1592        }
1593    }
1594
1595    private void offsetChildrenPrimary(int increment) {
1596        final int childCount = getChildCount();
1597        if (mOrientation == VERTICAL) {
1598            for (int i = 0; i < childCount; i++) {
1599                getChildAt(i).offsetTopAndBottom(increment);
1600            }
1601        } else {
1602            for (int i = 0; i < childCount; i++) {
1603                getChildAt(i).offsetLeftAndRight(increment);
1604            }
1605        }
1606    }
1607
1608    @Override
1609    public int scrollHorizontallyBy(int dx, Recycler recycler, RecyclerView.State state) {
1610        if (DEBUG) Log.v(getTag(), "scrollHorizontallyBy " + dx);
1611        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1612            return 0;
1613        }
1614        saveContext(recycler, state);
1615        int result;
1616        if (mOrientation == HORIZONTAL) {
1617            result = scrollDirectionPrimary(dx);
1618        } else {
1619            result = scrollDirectionSecondary(dx);
1620        }
1621        leaveContext();
1622        return result;
1623    }
1624
1625    @Override
1626    public int scrollVerticallyBy(int dy, Recycler recycler, RecyclerView.State state) {
1627        if (DEBUG) Log.v(getTag(), "scrollVerticallyBy " + dy);
1628        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1629            return 0;
1630        }
1631        saveContext(recycler, state);
1632        int result;
1633        if (mOrientation == VERTICAL) {
1634            result = scrollDirectionPrimary(dy);
1635        } else {
1636            result = scrollDirectionSecondary(dy);
1637        }
1638        leaveContext();
1639        return result;
1640    }
1641
1642    // scroll in main direction may add/prune views
1643    private int scrollDirectionPrimary(int da) {
1644        if (da > 0) {
1645            if (!mWindowAlignment.mainAxis().isMaxUnknown()) {
1646                int maxScroll = mWindowAlignment.mainAxis().getMaxScroll();
1647                if (mScrollOffsetPrimary + da > maxScroll) {
1648                    da = maxScroll - mScrollOffsetPrimary;
1649                }
1650            }
1651        } else if (da < 0) {
1652            if (!mWindowAlignment.mainAxis().isMinUnknown()) {
1653                int minScroll = mWindowAlignment.mainAxis().getMinScroll();
1654                if (mScrollOffsetPrimary + da < minScroll) {
1655                    da = minScroll - mScrollOffsetPrimary;
1656                }
1657            }
1658        }
1659        if (da == 0) {
1660            return 0;
1661        }
1662        offsetChildrenPrimary(-da);
1663        mScrollOffsetPrimary += da;
1664        if (mInLayout) {
1665            return da;
1666        }
1667
1668        int childCount = getChildCount();
1669        boolean updated;
1670
1671        if (da > 0) {
1672            appendVisibleItems();
1673        } else if (da < 0) {
1674            prependVisibleItems();
1675        }
1676        updated = getChildCount() > childCount;
1677        childCount = getChildCount();
1678
1679        if (da > 0) {
1680            removeInvisibleViewsAtFront();
1681        } else if (da < 0) {
1682            removeInvisibleViewsAtEnd();
1683        }
1684        updated |= getChildCount() < childCount;
1685
1686        if (updated) {
1687            updateRowSecondarySizeRefresh();
1688        }
1689
1690        mBaseGridView.invalidate();
1691        return da;
1692    }
1693
1694    // scroll in second direction will not add/prune views
1695    private int scrollDirectionSecondary(int dy) {
1696        if (dy == 0) {
1697            return 0;
1698        }
1699        offsetChildrenSecondary(-dy);
1700        mScrollOffsetSecondary += dy;
1701        mBaseGridView.invalidate();
1702        return dy;
1703    }
1704
1705    private void updateScrollMax() {
1706        if (mLastVisiblePos < 0) {
1707            return;
1708        }
1709        final boolean lastAvailable = mLastVisiblePos == mState.getItemCount() - 1;
1710        final boolean maxUnknown = mWindowAlignment.mainAxis().isMaxUnknown();
1711        if (!lastAvailable && maxUnknown) {
1712            return;
1713        }
1714        int maxEdge = Integer.MIN_VALUE;
1715        int rowIndex = -1;
1716        for (int i = 0; i < mRows.length; i++) {
1717            if (mRows[i].high > maxEdge) {
1718                maxEdge = mRows[i].high;
1719                rowIndex = i;
1720            }
1721        }
1722        int maxScroll = Integer.MAX_VALUE;
1723        for (int i = mLastVisiblePos; i >= mFirstVisiblePos; i--) {
1724            StaggeredGrid.Location location = mGrid.getLocation(i);
1725            if (location != null && location.row == rowIndex) {
1726                int savedMaxEdge = mWindowAlignment.mainAxis().getMaxEdge();
1727                mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1728                maxScroll = getPrimarySystemScrollPosition(findViewByPosition(i));
1729                mWindowAlignment.mainAxis().setMaxEdge(savedMaxEdge);
1730                break;
1731            }
1732        }
1733        if (lastAvailable) {
1734            mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1735            mWindowAlignment.mainAxis().setMaxScroll(maxScroll);
1736            if (DEBUG) Log.v(getTag(), "updating scroll maxEdge to " + maxEdge +
1737                    " scrollMax to " + maxScroll);
1738        } else {
1739            // the maxScroll for currently last visible item is larger,
1740            // so we must invalidate the max scroll value.
1741            if (maxScroll > mWindowAlignment.mainAxis().getMaxScroll()) {
1742                mWindowAlignment.mainAxis().invalidateScrollMax();
1743                if (DEBUG) Log.v(getTag(), "Invalidate scrollMax since it should be "
1744                        + "greater than " + maxScroll);
1745            }
1746        }
1747    }
1748
1749    private void updateScrollMin() {
1750        if (mFirstVisiblePos < 0) {
1751            return;
1752        }
1753        final boolean firstAvailable = mFirstVisiblePos == 0;
1754        final boolean minUnknown = mWindowAlignment.mainAxis().isMinUnknown();
1755        if (!firstAvailable && minUnknown) {
1756            return;
1757        }
1758        int minEdge = Integer.MAX_VALUE;
1759        int rowIndex = -1;
1760        for (int i = 0; i < mRows.length; i++) {
1761            if (mRows[i].low < minEdge) {
1762                minEdge = mRows[i].low;
1763                rowIndex = i;
1764            }
1765        }
1766        int minScroll = Integer.MIN_VALUE;
1767        for (int i = mFirstVisiblePos; i <= mLastVisiblePos; i++) {
1768            StaggeredGrid.Location location = mGrid.getLocation(i);
1769            if (location != null && location.row == rowIndex) {
1770                int savedMinEdge = mWindowAlignment.mainAxis().getMinEdge();
1771                mWindowAlignment.mainAxis().setMinEdge(minEdge);
1772                minScroll = getPrimarySystemScrollPosition(findViewByPosition(i));
1773                mWindowAlignment.mainAxis().setMinEdge(savedMinEdge);
1774                break;
1775            }
1776        }
1777        if (firstAvailable) {
1778            mWindowAlignment.mainAxis().setMinEdge(minEdge);
1779            mWindowAlignment.mainAxis().setMinScroll(minScroll);
1780            if (DEBUG) Log.v(getTag(), "updating scroll minEdge to " + minEdge +
1781                    " scrollMin to " + minScroll);
1782        } else {
1783            // the minScroll for currently first visible item is smaller,
1784            // so we must invalidate the min scroll value.
1785            if (minScroll < mWindowAlignment.mainAxis().getMinScroll()) {
1786                mWindowAlignment.mainAxis().invalidateScrollMin();
1787                if (DEBUG) Log.v(getTag(), "Invalidate scrollMin, since it should be "
1788                        + "less than " + minScroll);
1789            }
1790        }
1791    }
1792
1793    private void updateScrollSecondAxis() {
1794        mWindowAlignment.secondAxis().setMinEdge(0);
1795        mWindowAlignment.secondAxis().setMaxEdge(getSizeSecondary());
1796    }
1797
1798    private void initScrollController() {
1799        // mScrollOffsetPrimary and mScrollOffsetSecondary includes the padding.
1800        // e.g. when topPadding is 16 for horizontal grid view,  the initial
1801        // mScrollOffsetSecondary is -16.  fastLayout() put views based on offsets(not padding),
1802        // when padding changes to 20,  we also need update mScrollOffsetSecondary to -20 before
1803        // fastLayout() is performed
1804        int paddingPrimaryDiff, paddingSecondaryDiff;
1805        if (mOrientation == HORIZONTAL) {
1806            paddingPrimaryDiff = getPaddingLeft() - mWindowAlignment.horizontal.getPaddingLow();
1807            paddingSecondaryDiff = getPaddingTop() - mWindowAlignment.vertical.getPaddingLow();
1808        } else {
1809            paddingPrimaryDiff = getPaddingTop() - mWindowAlignment.vertical.getPaddingLow();
1810            paddingSecondaryDiff = getPaddingLeft() - mWindowAlignment.horizontal.getPaddingLow();
1811        }
1812        mScrollOffsetPrimary -= paddingPrimaryDiff;
1813        mScrollOffsetSecondary -= paddingSecondaryDiff;
1814
1815        mWindowAlignment.horizontal.setSize(getWidth());
1816        mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight());
1817        mWindowAlignment.vertical.setSize(getHeight());
1818        mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom());
1819        mSizePrimary = mWindowAlignment.mainAxis().getSize();
1820
1821        if (DEBUG) {
1822            Log.v(getTag(), "initScrollController mSizePrimary " + mSizePrimary
1823                    + " mWindowAlignment " + mWindowAlignment);
1824        }
1825    }
1826
1827    public void setSelection(RecyclerView parent, int position) {
1828        setSelection(parent, position, false);
1829    }
1830
1831    public void setSelectionSmooth(RecyclerView parent, int position) {
1832        setSelection(parent, position, true);
1833    }
1834
1835    public int getSelection() {
1836        return mFocusPosition;
1837    }
1838
1839    public void setSelection(RecyclerView parent, int position, boolean smooth) {
1840        if (mFocusPosition == position) {
1841            return;
1842        }
1843        View view = findViewByPosition(position);
1844        if (view != null) {
1845            mInSelection = true;
1846            scrollToView(view, smooth);
1847            mInSelection = false;
1848        } else {
1849            mFocusPosition = position;
1850            mFocusPositionOffset = 0;
1851            if (!mLayoutEnabled) {
1852                return;
1853            }
1854            if (smooth) {
1855                if (!hasDoneFirstLayout()) {
1856                    Log.w(getTag(), "setSelectionSmooth should " +
1857                            "not be called before first layout pass");
1858                    return;
1859                }
1860                LinearSmoothScroller linearSmoothScroller =
1861                        new LinearSmoothScroller(parent.getContext()) {
1862                    @Override
1863                    public PointF computeScrollVectorForPosition(int targetPosition) {
1864                        if (getChildCount() == 0) {
1865                            return null;
1866                        }
1867                        final int firstChildPos = getPosition(getChildAt(0));
1868                        final int direction = targetPosition < firstChildPos ? -1 : 1;
1869                        if (mOrientation == HORIZONTAL) {
1870                            return new PointF(direction, 0);
1871                        } else {
1872                            return new PointF(0, direction);
1873                        }
1874                    }
1875                    @Override
1876                    protected void onTargetFound(View targetView,
1877                            RecyclerView.State state, Action action) {
1878                        if (hasFocus()) {
1879                            targetView.requestFocus();
1880                        }
1881                        dispatchChildSelected();
1882                        if (getScrollPosition(targetView, mTempDeltas)) {
1883                            int dx, dy;
1884                            if (mOrientation == HORIZONTAL) {
1885                                dx = mTempDeltas[0];
1886                                dy = mTempDeltas[1];
1887                            } else {
1888                                dx = mTempDeltas[1];
1889                                dy = mTempDeltas[0];
1890                            }
1891                            final int distance = (int) Math.sqrt(dx * dx + dy * dy);
1892                            final int time = calculateTimeForDeceleration(distance);
1893                            action.update(dx, dy, time, mDecelerateInterpolator);
1894                        }
1895                    }
1896                };
1897                linearSmoothScroller.setTargetPosition(position);
1898                startSmoothScroll(linearSmoothScroller);
1899            } else {
1900                mForceFullLayout = true;
1901                parent.requestLayout();
1902            }
1903        }
1904    }
1905
1906    @Override
1907    public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
1908        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
1909            int pos = mFocusPosition + mFocusPositionOffset;
1910            if (positionStart <= pos) {
1911                mFocusPositionOffset += itemCount;
1912            }
1913        }
1914    }
1915
1916    @Override
1917    public void onItemsChanged(RecyclerView recyclerView) {
1918        mFocusPositionOffset = 0;
1919        mChildrenStates.clear();
1920    }
1921
1922    @Override
1923    public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) {
1924        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
1925            int pos = mFocusPosition + mFocusPositionOffset;
1926            if (positionStart <= pos) {
1927                if (positionStart + itemCount > pos) {
1928                    // stop updating offset after the focus item was removed
1929                    mFocusPositionOffset = Integer.MIN_VALUE;
1930                } else {
1931                    mFocusPositionOffset -= itemCount;
1932                }
1933            }
1934        }
1935        for (int i = 0; i < itemCount; i++) {
1936            mChildrenStates.remove(positionStart + i);
1937        }
1938    }
1939
1940    public void onItemsMoved(RecyclerView recyclerView, int fromPosition, int toPosition,
1941            int itemCount) {
1942        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
1943            int pos = mFocusPosition + mFocusPositionOffset;
1944            if (fromPosition <= pos && pos < fromPosition + itemCount) {
1945                // moved items include focused position
1946                mFocusPositionOffset += toPosition - fromPosition;
1947            } else if (fromPosition < pos && toPosition > pos - itemCount) {
1948                // move items before focus position to after focused position
1949                mFocusPositionOffset -= itemCount;
1950            } else if (fromPosition > pos && toPosition < pos) {
1951                // move items after focus position to before focused position
1952                mFocusPositionOffset += itemCount;
1953            }
1954        }
1955    }
1956
1957    @Override
1958    public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) {
1959        if (mFocusSearchDisabled) {
1960            return true;
1961        }
1962        if (!mInLayout && !mInSelection) {
1963            scrollToView(child, true);
1964        }
1965        return true;
1966    }
1967
1968    @Override
1969    public boolean requestChildRectangleOnScreen(RecyclerView parent, View view, Rect rect,
1970            boolean immediate) {
1971        if (DEBUG) Log.v(getTag(), "requestChildRectangleOnScreen " + view + " " + rect);
1972        return false;
1973    }
1974
1975    int getScrollOffsetX() {
1976        return mOrientation == HORIZONTAL ? mScrollOffsetPrimary : mScrollOffsetSecondary;
1977    }
1978
1979    int getScrollOffsetY() {
1980        return mOrientation == HORIZONTAL ? mScrollOffsetSecondary : mScrollOffsetPrimary;
1981    }
1982
1983    public void getViewSelectedOffsets(View view, int[] offsets) {
1984        if (mOrientation == HORIZONTAL) {
1985            offsets[0] = getPrimarySystemScrollPosition(view) - mScrollOffsetPrimary;
1986            offsets[1] = getSecondarySystemScrollPosition(view) - mScrollOffsetSecondary;
1987        } else {
1988            offsets[1] = getPrimarySystemScrollPosition(view) - mScrollOffsetPrimary;
1989            offsets[0] = getSecondarySystemScrollPosition(view) - mScrollOffsetSecondary;
1990        }
1991    }
1992
1993    private int getPrimarySystemScrollPosition(View view) {
1994        int viewCenterPrimary = mScrollOffsetPrimary + getViewCenter(view);
1995        int pos = getPositionByView(view);
1996        StaggeredGrid.Location location = mGrid.getLocation(pos);
1997        final int row = location.row;
1998        boolean isFirst = mFirstVisiblePos == 0;
1999        // TODO: change to use State object in onRequestChildFocus()
2000        boolean isLast = mLastVisiblePos == (mState == null ?
2001                getItemCount() : mState.getItemCount()) - 1;
2002        if (isFirst || isLast) {
2003            for (int i = getChildCount() - 1; i >= 0; i--) {
2004                int position = getPositionByIndex(i);
2005                StaggeredGrid.Location loc = mGrid.getLocation(position);
2006                if (loc != null && loc.row == row) {
2007                    if (position < pos) {
2008                        isFirst = false;
2009                    } else if (position > pos) {
2010                        isLast = false;
2011                    }
2012                }
2013            }
2014        }
2015        return mWindowAlignment.mainAxis().getSystemScrollPos(viewCenterPrimary, isFirst, isLast);
2016    }
2017
2018    private int getSecondarySystemScrollPosition(View view) {
2019        int viewCenterSecondary = mScrollOffsetSecondary + getViewCenterSecondary(view);
2020        int pos = getPositionByView(view);
2021        StaggeredGrid.Location location = mGrid.getLocation(pos);
2022        final int row = location.row;
2023        boolean isFirst = row == 0;
2024        boolean isLast = row == mGrid.getNumRows() - 1;
2025        return mWindowAlignment.secondAxis().getSystemScrollPos(viewCenterSecondary,
2026                isFirst, isLast);
2027    }
2028
2029    /**
2030     * Scroll to a given child view and change mFocusPosition.
2031     */
2032    private void scrollToView(View view, boolean smooth) {
2033        int newFocusPosition = getPositionByView(view);
2034        if (newFocusPosition != mFocusPosition) {
2035            mFocusPosition = newFocusPosition;
2036            mFocusPositionOffset = 0;
2037            if (!mInLayout) {
2038                dispatchChildSelected();
2039            }
2040        }
2041        if (mBaseGridView.isChildrenDrawingOrderEnabledInternal()) {
2042            mBaseGridView.invalidate();
2043        }
2044        if (view == null) {
2045            return;
2046        }
2047        if (!view.hasFocus() && mBaseGridView.hasFocus()) {
2048            // transfer focus to the child if it does not have focus yet (e.g. triggered
2049            // by setSelection())
2050            view.requestFocus();
2051        }
2052        if (!mScrollEnabled) {
2053            return;
2054        }
2055        if (getScrollPosition(view, mTempDeltas)) {
2056            scrollGrid(mTempDeltas[0], mTempDeltas[1], smooth);
2057        }
2058    }
2059
2060    private boolean getScrollPosition(View view, int[] deltas) {
2061        switch (mFocusScrollStrategy) {
2062        case BaseGridView.FOCUS_SCROLL_ALIGNED:
2063        default:
2064            return getAlignedPosition(view, deltas);
2065        case BaseGridView.FOCUS_SCROLL_ITEM:
2066        case BaseGridView.FOCUS_SCROLL_PAGE:
2067            return getNoneAlignedPosition(view, deltas);
2068        }
2069    }
2070
2071    private boolean getNoneAlignedPosition(View view, int[] deltas) {
2072        int pos = getPositionByView(view);
2073        int viewMin = getViewMin(view);
2074        int viewMax = getViewMax(view);
2075        // we either align "firstView" to left/top padding edge
2076        // or align "lastView" to right/bottom padding edge
2077        View firstView = null;
2078        View lastView = null;
2079        int paddingLow = mWindowAlignment.mainAxis().getPaddingLow();
2080        int clientSize = mWindowAlignment.mainAxis().getClientSize();
2081        final int row = mGrid.getLocation(pos).row;
2082        if (viewMin < paddingLow) {
2083            // view enters low padding area:
2084            firstView = view;
2085            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
2086                // scroll one "page" left/top,
2087                // align first visible item of the "page" at the low padding edge.
2088                while (!prependOneVisibleItem()) {
2089                    List<Integer> positions =
2090                            mGrid.getItemPositionsInRows(mFirstVisiblePos, pos)[row];
2091                    firstView = findViewByPosition(positions.get(0));
2092                    if (viewMax - getViewMin(firstView) > clientSize) {
2093                        if (positions.size() > 1) {
2094                            firstView = findViewByPosition(positions.get(1));
2095                        }
2096                        break;
2097                    }
2098                }
2099            }
2100        } else if (viewMax > clientSize + paddingLow) {
2101            // view enters high padding area:
2102            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
2103                // scroll whole one page right/bottom, align view at the low padding edge.
2104                firstView = view;
2105                do {
2106                    List<Integer> positions =
2107                            mGrid.getItemPositionsInRows(pos, mLastVisiblePos)[row];
2108                    lastView = findViewByPosition(positions.get(positions.size() - 1));
2109                    if (getViewMax(lastView) - viewMin > clientSize) {
2110                        lastView = null;
2111                        break;
2112                    }
2113                } while (!appendOneVisibleItem());
2114                if (lastView != null) {
2115                    // however if we reached end,  we should align last view.
2116                    firstView = null;
2117                }
2118            } else {
2119                lastView = view;
2120            }
2121        }
2122        int scrollPrimary = 0;
2123        int scrollSecondary = 0;
2124        if (firstView != null) {
2125            scrollPrimary = getViewMin(firstView) - paddingLow;
2126        } else if (lastView != null) {
2127            scrollPrimary = getViewMax(lastView) - (paddingLow + clientSize);
2128        }
2129        View secondaryAlignedView;
2130        if (firstView != null) {
2131            secondaryAlignedView = firstView;
2132        } else if (lastView != null) {
2133            secondaryAlignedView = lastView;
2134        } else {
2135            secondaryAlignedView = view;
2136        }
2137        scrollSecondary = getSecondarySystemScrollPosition(secondaryAlignedView);
2138        scrollSecondary -= mScrollOffsetSecondary;
2139        if (scrollPrimary != 0 || scrollSecondary != 0) {
2140            deltas[0] = scrollPrimary;
2141            deltas[1] = scrollSecondary;
2142            return true;
2143        }
2144        return false;
2145    }
2146
2147    private boolean getAlignedPosition(View view, int[] deltas) {
2148        int scrollPrimary = getPrimarySystemScrollPosition(view);
2149        int scrollSecondary = getSecondarySystemScrollPosition(view);
2150        if (DEBUG) {
2151            Log.v(getTag(), "getAlignedPosition " + scrollPrimary + " " + scrollSecondary
2152                    +" " + mWindowAlignment);
2153        }
2154        scrollPrimary -= mScrollOffsetPrimary;
2155        scrollSecondary -= mScrollOffsetSecondary;
2156        if (scrollPrimary != 0 || scrollSecondary != 0) {
2157            deltas[0] = scrollPrimary;
2158            deltas[1] = scrollSecondary;
2159            return true;
2160        }
2161        return false;
2162    }
2163
2164    private void scrollGrid(int scrollPrimary, int scrollSecondary, boolean smooth) {
2165        if (mInLayout) {
2166            scrollDirectionPrimary(scrollPrimary);
2167            scrollDirectionSecondary(scrollSecondary);
2168        } else {
2169            int scrollX;
2170            int scrollY;
2171            if (mOrientation == HORIZONTAL) {
2172                scrollX = scrollPrimary;
2173                scrollY = scrollSecondary;
2174            } else {
2175                scrollX = scrollSecondary;
2176                scrollY = scrollPrimary;
2177            }
2178            if (smooth) {
2179                mBaseGridView.smoothScrollBy(scrollX, scrollY);
2180            } else {
2181                mBaseGridView.scrollBy(scrollX, scrollY);
2182            }
2183        }
2184    }
2185
2186    public void setPruneChild(boolean pruneChild) {
2187        if (mPruneChild != pruneChild) {
2188            mPruneChild = pruneChild;
2189            if (mPruneChild) {
2190                requestLayout();
2191            }
2192        }
2193    }
2194
2195    public boolean getPruneChild() {
2196        return mPruneChild;
2197    }
2198
2199    public void setScrollEnabled(boolean scrollEnabled) {
2200        if (mScrollEnabled != scrollEnabled) {
2201            mScrollEnabled = scrollEnabled;
2202            if (mScrollEnabled && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
2203                View focusView = findViewByPosition(mFocusPosition == NO_POSITION ? 0 :
2204                    mFocusPosition);
2205                if (focusView != null) {
2206                    scrollToView(focusView, true);
2207                }
2208            }
2209        }
2210    }
2211
2212    public boolean isScrollEnabled() {
2213        return mScrollEnabled;
2214    }
2215
2216    private int findImmediateChildIndex(View view) {
2217        while (view != null && view != mBaseGridView) {
2218            int index = mBaseGridView.indexOfChild(view);
2219            if (index >= 0) {
2220                return index;
2221            }
2222            view = (View) view.getParent();
2223        }
2224        return NO_POSITION;
2225    }
2226
2227    void setFocusSearchDisabled(boolean disabled) {
2228        mFocusSearchDisabled = disabled;
2229    }
2230
2231    boolean isFocusSearchDisabled() {
2232        return mFocusSearchDisabled;
2233    }
2234
2235    @Override
2236    public View onInterceptFocusSearch(View focused, int direction) {
2237        if (mFocusSearchDisabled) {
2238            return focused;
2239        }
2240        return null;
2241    }
2242
2243    boolean hasPreviousViewInSameRow(int pos) {
2244        if (mGrid == null || pos == NO_POSITION) {
2245            return false;
2246        }
2247        if (mFirstVisiblePos > 0) {
2248            return true;
2249        }
2250        final int focusedRow = mGrid.getLocation(pos).row;
2251        for (int i = getChildCount() - 1; i >= 0; i--) {
2252            int position = getPositionByIndex(i);
2253            StaggeredGrid.Location loc = mGrid.getLocation(position);
2254            if (loc != null && loc.row == focusedRow) {
2255                if (position < pos) {
2256                    return true;
2257                }
2258            }
2259        }
2260        return false;
2261    }
2262
2263    @Override
2264    public boolean onAddFocusables(RecyclerView recyclerView,
2265            ArrayList<View> views, int direction, int focusableMode) {
2266        if (mFocusSearchDisabled) {
2267            return true;
2268        }
2269        // If this viewgroup or one of its children currently has focus then we
2270        // consider our children for focus searching in main direction on the same row.
2271        // If this viewgroup has no focus and using focus align, we want the system
2272        // to ignore our children and pass focus to the viewgroup, which will pass
2273        // focus on to its children appropriately.
2274        // If this viewgroup has no focus and not using focus align, we want to
2275        // consider the child that does not overlap with padding area.
2276        if (recyclerView.hasFocus()) {
2277            final int movement = getMovement(direction);
2278            if (movement != PREV_ITEM && movement != NEXT_ITEM) {
2279                // Move on secondary direction uses default addFocusables().
2280                return false;
2281            }
2282            final View focused = recyclerView.findFocus();
2283            final int focusedPos = getPositionByIndex(findImmediateChildIndex(focused));
2284            // Add focusables of focused item.
2285            if (focusedPos != NO_POSITION) {
2286                findViewByPosition(focusedPos).addFocusables(views,  direction, focusableMode);
2287            }
2288            final int focusedRow = mGrid != null && focusedPos != NO_POSITION ?
2289                    mGrid.getLocation(focusedPos).row : NO_POSITION;
2290            // Add focusables of next neighbor of same row on the focus search direction.
2291            if (mGrid != null) {
2292                final int focusableCount = views.size();
2293                for (int i = 0, count = getChildCount(); i < count; i++) {
2294                    int index = movement == NEXT_ITEM ? i : count - 1 - i;
2295                    final View child = getChildAt(index);
2296                    if (child.getVisibility() != View.VISIBLE) {
2297                        continue;
2298                    }
2299                    int position = getPositionByIndex(index);
2300                    StaggeredGrid.Location loc = mGrid.getLocation(position);
2301                    if (focusedRow == NO_POSITION || (loc != null && loc.row == focusedRow)) {
2302                        if (focusedPos == NO_POSITION ||
2303                                (movement == NEXT_ITEM && position > focusedPos)
2304                                || (movement == PREV_ITEM && position < focusedPos)) {
2305                            child.addFocusables(views,  direction, focusableMode);
2306                            if (views.size() > focusableCount) {
2307                                break;
2308                            }
2309                        }
2310                    }
2311                }
2312            }
2313        } else {
2314            if (mFocusScrollStrategy != BaseGridView.FOCUS_SCROLL_ALIGNED) {
2315                // adding views not overlapping padding area to avoid scrolling in gaining focus
2316                int left = mWindowAlignment.mainAxis().getPaddingLow();
2317                int right = mWindowAlignment.mainAxis().getClientSize() + left;
2318                int focusableCount = views.size();
2319                for (int i = 0, count = getChildCount(); i < count; i++) {
2320                    View child = getChildAt(i);
2321                    if (child.getVisibility() == View.VISIBLE) {
2322                        if (getViewMin(child) >= left && getViewMax(child) <= right) {
2323                            child.addFocusables(views, direction, focusableMode);
2324                        }
2325                    }
2326                }
2327                // if we cannot find any, then just add all children.
2328                if (views.size() == focusableCount) {
2329                    for (int i = 0, count = getChildCount(); i < count; i++) {
2330                        View child = getChildAt(i);
2331                        if (child.getVisibility() == View.VISIBLE) {
2332                            child.addFocusables(views, direction, focusableMode);
2333                        }
2334                    }
2335                    if (views.size() != focusableCount) {
2336                        return true;
2337                    }
2338                } else {
2339                    return true;
2340                }
2341                // if still cannot find any, fall through and add itself
2342            }
2343            if (recyclerView.isFocusable()) {
2344                views.add(recyclerView);
2345            }
2346        }
2347        return true;
2348    }
2349
2350    @Override
2351    public View onFocusSearchFailed(View focused, int direction, Recycler recycler,
2352            RecyclerView.State state) {
2353        if (DEBUG) Log.v(getTag(), "onFocusSearchFailed direction " + direction);
2354
2355        View view = null;
2356        int movement = getMovement(direction);
2357        if (mNumRows == 1) {
2358            // for simple row, use LinearSmoothScroller to smooth animation.
2359            // It will stay at a fixed cap speed in continuous scroll.
2360            if (movement == NEXT_ITEM) {
2361                int newPos = mFocusPosition + mNumRows;
2362                if (newPos < getItemCount()) {
2363                    setSelectionSmooth(mBaseGridView, newPos);
2364                    view = focused;
2365                } else {
2366                    if (!mFocusOutEnd) {
2367                        view = focused;
2368                    }
2369                }
2370            } else if (movement == PREV_ITEM){
2371                int newPos = mFocusPosition - mNumRows;
2372                if (newPos >= 0) {
2373                    setSelectionSmooth(mBaseGridView, newPos);
2374                    view = focused;
2375                } else {
2376                    if (!mFocusOutFront) {
2377                        view = focused;
2378                    }
2379                }
2380            }
2381        } else if (mNumRows > 1) {
2382            // for possible staggered grid,  we need guarantee focus to same row/column.
2383            // TODO: we may also use LinearSmoothScroller.
2384            saveContext(recycler, state);
2385            final FocusFinder ff = FocusFinder.getInstance();
2386            if (movement == NEXT_ITEM) {
2387                while (view == null && !appendOneVisibleItem()) {
2388                    view = ff.findNextFocus(mBaseGridView, focused, direction);
2389                }
2390            } else if (movement == PREV_ITEM){
2391                while (view == null && !prependOneVisibleItem()) {
2392                    view = ff.findNextFocus(mBaseGridView, focused, direction);
2393                }
2394            }
2395            if (view == null) {
2396                // returning the same view to prevent focus lost when scrolling past the end of the list
2397                if (movement == PREV_ITEM) {
2398                    view = mFocusOutFront ? null : focused;
2399                } else if (movement == NEXT_ITEM){
2400                    view = mFocusOutEnd ? null : focused;
2401                }
2402            }
2403            leaveContext();
2404        }
2405        if (DEBUG) Log.v(getTag(), "returning view " + view);
2406        return view;
2407    }
2408
2409    boolean gridOnRequestFocusInDescendants(RecyclerView recyclerView, int direction,
2410            Rect previouslyFocusedRect) {
2411        switch (mFocusScrollStrategy) {
2412        case BaseGridView.FOCUS_SCROLL_ALIGNED:
2413        default:
2414            return gridOnRequestFocusInDescendantsAligned(recyclerView,
2415                    direction, previouslyFocusedRect);
2416        case BaseGridView.FOCUS_SCROLL_PAGE:
2417        case BaseGridView.FOCUS_SCROLL_ITEM:
2418            return gridOnRequestFocusInDescendantsUnaligned(recyclerView,
2419                    direction, previouslyFocusedRect);
2420        }
2421    }
2422
2423    private boolean gridOnRequestFocusInDescendantsAligned(RecyclerView recyclerView,
2424            int direction, Rect previouslyFocusedRect) {
2425        View view = findViewByPosition(mFocusPosition);
2426        if (view != null) {
2427            boolean result = view.requestFocus(direction, previouslyFocusedRect);
2428            if (!result && DEBUG) {
2429                Log.w(getTag(), "failed to request focus on " + view);
2430            }
2431            return result;
2432        }
2433        return false;
2434    }
2435
2436    private boolean gridOnRequestFocusInDescendantsUnaligned(RecyclerView recyclerView,
2437            int direction, Rect previouslyFocusedRect) {
2438        // focus to view not overlapping padding area to avoid scrolling in gaining focus
2439        int index;
2440        int increment;
2441        int end;
2442        int count = getChildCount();
2443        if ((direction & View.FOCUS_FORWARD) != 0) {
2444            index = 0;
2445            increment = 1;
2446            end = count;
2447        } else {
2448            index = count - 1;
2449            increment = -1;
2450            end = -1;
2451        }
2452        int left = mWindowAlignment.mainAxis().getPaddingLow();
2453        int right = mWindowAlignment.mainAxis().getClientSize() + left;
2454        for (int i = index; i != end; i += increment) {
2455            View child = getChildAt(i);
2456            if (child.getVisibility() == View.VISIBLE) {
2457                if (getViewMin(child) >= left && getViewMax(child) <= right) {
2458                    if (child.requestFocus(direction, previouslyFocusedRect)) {
2459                        return true;
2460                    }
2461                }
2462            }
2463        }
2464        return false;
2465    }
2466
2467    private final static int PREV_ITEM = 0;
2468    private final static int NEXT_ITEM = 1;
2469    private final static int PREV_ROW = 2;
2470    private final static int NEXT_ROW = 3;
2471
2472    private int getMovement(int direction) {
2473        int movement = View.FOCUS_LEFT;
2474
2475        if (mOrientation == HORIZONTAL) {
2476            switch(direction) {
2477                case View.FOCUS_LEFT:
2478                    movement = PREV_ITEM;
2479                    break;
2480                case View.FOCUS_RIGHT:
2481                    movement = NEXT_ITEM;
2482                    break;
2483                case View.FOCUS_UP:
2484                    movement = PREV_ROW;
2485                    break;
2486                case View.FOCUS_DOWN:
2487                    movement = NEXT_ROW;
2488                    break;
2489            }
2490         } else if (mOrientation == VERTICAL) {
2491             switch(direction) {
2492                 case View.FOCUS_LEFT:
2493                     movement = PREV_ROW;
2494                     break;
2495                 case View.FOCUS_RIGHT:
2496                     movement = NEXT_ROW;
2497                     break;
2498                 case View.FOCUS_UP:
2499                     movement = PREV_ITEM;
2500                     break;
2501                 case View.FOCUS_DOWN:
2502                     movement = NEXT_ITEM;
2503                     break;
2504             }
2505         }
2506
2507        return movement;
2508    }
2509
2510    int getChildDrawingOrder(RecyclerView recyclerView, int childCount, int i) {
2511        View view = findViewByPosition(mFocusPosition);
2512        if (view == null) {
2513            return i;
2514        }
2515        int focusIndex = recyclerView.indexOfChild(view);
2516        // supposely 0 1 2 3 4 5 6 7 8 9, 4 is the center item
2517        // drawing order is 0 1 2 3 9 8 7 6 5 4
2518        if (i < focusIndex) {
2519            return i;
2520        } else if (i < childCount - 1) {
2521            return focusIndex + childCount - 1 - i;
2522        } else {
2523            return focusIndex;
2524        }
2525    }
2526
2527    @Override
2528    public void onAdapterChanged(RecyclerView.Adapter oldAdapter,
2529            RecyclerView.Adapter newAdapter) {
2530        discardLayoutInfo();
2531        mFocusPosition = NO_POSITION;
2532        mFocusPositionOffset = 0;
2533        mLoadingState = null;
2534        mChildrenStates.clear();
2535        super.onAdapterChanged(oldAdapter, newAdapter);
2536    }
2537
2538    private void discardLayoutInfo() {
2539        mGrid = null;
2540        mRows = null;
2541        mRowSizeSecondary = null;
2542        mFirstVisiblePos = -1;
2543        mLastVisiblePos = -1;
2544        mRowSecondarySizeRefresh = false;
2545    }
2546
2547    public void setLayoutEnabled(boolean layoutEnabled) {
2548        if (mLayoutEnabled != layoutEnabled) {
2549            mLayoutEnabled = layoutEnabled;
2550            requestLayout();
2551        }
2552    }
2553
2554    final static class SavedState implements Parcelable {
2555
2556        int index; // index inside adapter of the current view
2557        Bundle childStates = Bundle.EMPTY;
2558
2559        @Override
2560        public void writeToParcel(Parcel out, int flags) {
2561            out.writeInt(index);
2562            out.writeBundle(childStates);
2563        }
2564
2565        @SuppressWarnings("hiding")
2566        public static final Parcelable.Creator<SavedState> CREATOR =
2567                new Parcelable.Creator<SavedState>() {
2568                    @Override
2569                    public SavedState createFromParcel(Parcel in) {
2570                        return new SavedState(in);
2571                    }
2572
2573                    @Override
2574                    public SavedState[] newArray(int size) {
2575                        return new SavedState[size];
2576                    }
2577                };
2578
2579        @Override
2580        public int describeContents() {
2581            return 0;
2582        }
2583
2584        SavedState(Parcel in) {
2585            index = in.readInt();
2586            childStates = in.readBundle(GridLayoutManager.class.getClassLoader());
2587        }
2588
2589        SavedState() {
2590        }
2591    }
2592
2593    @Override
2594    public Parcelable onSaveInstanceState() {
2595        SavedState ss = new SavedState();
2596        for (int i = 0, count = getChildCount(); i < count; i++) {
2597            View view = getChildAt(i);
2598            int position = getPositionByView(view);
2599            if (position != NO_POSITION) {
2600                mChildrenStates.saveOnScreenView(view, position);
2601            }
2602        }
2603        ss.index = getSelection();
2604        ss.childStates = mChildrenStates.getChildStates();
2605        return ss;
2606    }
2607
2608    @Override
2609    public void onRestoreInstanceState(Parcelable state) {
2610        if (!(state instanceof SavedState)) {
2611            return;
2612        }
2613        SavedState ss = (SavedState)state;
2614        mLoadingState = ss;
2615        mForceFullLayout = true;
2616        requestLayout();
2617    }
2618}
2619