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