GridLayoutManager.java revision 906659fc65e7b8b1bc9f0c7cc3dabf7e64e8b9bf
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            if (append) {
1069                start = mRows[rowIndex].high;
1070                if (start != mRows[rowIndex].low) {
1071                    // if there are existing item in the row,  add margin between
1072                    start += mMarginPrimary;
1073                } else {
1074                    final int lastRow = mRows.length - 1;
1075                    if (lastRow != rowIndex && mRows[lastRow].high != mRows[lastRow].low) {
1076                        // if there are existing item in the last row, insert
1077                        // the new item after the last item of last row.
1078                        start = mRows[lastRow].high + mMarginPrimary;
1079                    }
1080                }
1081                end = start + length;
1082                mRows[rowIndex].high = end;
1083            } else {
1084                end = mRows[rowIndex].low;
1085                if (end != mRows[rowIndex].high) {
1086                    end -= mMarginPrimary;
1087                } else if (0 != rowIndex && mRows[0].high != mRows[0].low) {
1088                    // if there are existing item in the first row, insert
1089                    // the new item before the first item of first row.
1090                    end = mRows[0].low - mMarginPrimary;
1091                }
1092                start = end - length;
1093                mRows[rowIndex].low = start;
1094            }
1095            if (mFirstVisiblePos < 0) {
1096                mFirstVisiblePos = mLastVisiblePos = index;
1097            } else {
1098                if (append) {
1099                    mLastVisiblePos++;
1100                } else {
1101                    mFirstVisiblePos--;
1102                }
1103            }
1104            if (DEBUG) Log.v(getTag(), "start " + start + " end " + end);
1105            int startSecondary = getRowStartSecondary(rowIndex) - mScrollOffsetSecondary;
1106            layoutChild(rowIndex, v, start - mScrollOffsetPrimary, end - mScrollOffsetPrimary,
1107                    startSecondary);
1108            if (DEBUG) {
1109                Log.d(getTag(), "addView " + index + " " + v);
1110            }
1111            if (index == mFirstVisiblePos) {
1112                updateScrollMin();
1113            }
1114            if (index == mLastVisiblePos) {
1115                updateScrollMax();
1116            }
1117            mChildrenStates.loadView(v, index);
1118        }
1119    };
1120
1121    private void layoutChild(int rowIndex, View v, int start, int end, int startSecondary) {
1122        int sizeSecondary = mOrientation == HORIZONTAL ? v.getMeasuredHeight()
1123                : v.getMeasuredWidth();
1124        if (mFixedRowSizeSecondary > 0) {
1125            sizeSecondary = Math.min(sizeSecondary, mFixedRowSizeSecondary);
1126        }
1127        final int verticalGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
1128        final int horizontalGravity = mGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
1129        if (mOrientation == HORIZONTAL && verticalGravity == Gravity.TOP
1130                || mOrientation == VERTICAL && horizontalGravity == Gravity.LEFT) {
1131            // do nothing
1132        } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.BOTTOM
1133                || mOrientation == VERTICAL && horizontalGravity == Gravity.RIGHT) {
1134            startSecondary += getRowSizeSecondary(rowIndex) - sizeSecondary;
1135        } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.CENTER_VERTICAL
1136                || mOrientation == VERTICAL && horizontalGravity == Gravity.CENTER_HORIZONTAL) {
1137            startSecondary += (getRowSizeSecondary(rowIndex) - sizeSecondary) / 2;
1138        }
1139        int left, top, right, bottom;
1140        if (mOrientation == HORIZONTAL) {
1141            left = start;
1142            top = startSecondary;
1143            right = end;
1144            bottom = startSecondary + sizeSecondary;
1145        } else {
1146            top = start;
1147            left = startSecondary;
1148            bottom = end;
1149            right = startSecondary + sizeSecondary;
1150        }
1151        v.layout(left, top, right, bottom);
1152        updateChildOpticalInsets(v, left, top, right, bottom);
1153        updateChildAlignments(v);
1154    }
1155
1156    private void updateChildOpticalInsets(View v, int left, int top, int right, int bottom) {
1157        LayoutParams p = (LayoutParams) v.getLayoutParams();
1158        p.setOpticalInsets(left - v.getLeft(), top - v.getTop(),
1159                v.getRight() - right, v.getBottom() - bottom);
1160    }
1161
1162    private void updateChildAlignments(View v) {
1163        LayoutParams p = (LayoutParams) v.getLayoutParams();
1164        p.setAlignX(mItemAlignment.horizontal.getAlignmentPosition(v));
1165        p.setAlignY(mItemAlignment.vertical.getAlignmentPosition(v));
1166    }
1167
1168    private void updateChildAlignments() {
1169        for (int i = 0, c = getChildCount(); i < c; i++) {
1170            updateChildAlignments(getChildAt(i));
1171        }
1172    }
1173
1174    private boolean needsAppendVisibleItem() {
1175        if (mLastVisiblePos < mFocusPosition) {
1176            return true;
1177        }
1178        int right = mScrollOffsetPrimary + mSizePrimary;
1179        for (int i = 0; i < mNumRows; i++) {
1180            if (mRows[i].low == mRows[i].high) {
1181                if (mRows[i].high < right) {
1182                    return true;
1183                }
1184            } else if (mRows[i].high < right - mMarginPrimary) {
1185                return true;
1186            }
1187        }
1188        return false;
1189    }
1190
1191    private boolean needsPrependVisibleItem() {
1192        if (mFirstVisiblePos > mFocusPosition) {
1193            return true;
1194        }
1195        for (int i = 0; i < mNumRows; i++) {
1196            if (mRows[i].low == mRows[i].high) {
1197                if (mRows[i].low > mScrollOffsetPrimary) {
1198                    return true;
1199                }
1200            } else if (mRows[i].low - mMarginPrimary > mScrollOffsetPrimary) {
1201                return true;
1202            }
1203        }
1204        return false;
1205    }
1206
1207    // Append one column if possible and return true if reach end.
1208    private boolean appendOneVisibleItem() {
1209        while (true) {
1210            if (mLastVisiblePos != NO_POSITION && mLastVisiblePos < mState.getItemCount() -1 &&
1211                    mLastVisiblePos < mGrid.getLastIndex()) {
1212                // append invisible view of saved location till last row
1213                final int index = mLastVisiblePos + 1;
1214                final int row = mGrid.getLocation(index).row;
1215                mGridProvider.createItem(index, row, true);
1216                if (row == mNumRows - 1) {
1217                    return false;
1218                }
1219            } else if ((mLastVisiblePos == NO_POSITION && mState.getItemCount() > 0) ||
1220                    (mLastVisiblePos != NO_POSITION &&
1221                            mLastVisiblePos < mState.getItemCount() - 1)) {
1222                mGrid.appendItems(mScrollOffsetPrimary + mSizePrimary);
1223                return false;
1224            } else {
1225                return true;
1226            }
1227        }
1228    }
1229
1230    private void appendVisibleItems() {
1231        while (needsAppendVisibleItem()) {
1232            if (appendOneVisibleItem()) {
1233                break;
1234            }
1235        }
1236    }
1237
1238    // Prepend one column if possible and return true if reach end.
1239    private boolean prependOneVisibleItem() {
1240        while (true) {
1241            if (mFirstVisiblePos > 0) {
1242                if (mFirstVisiblePos > mGrid.getFirstIndex()) {
1243                    // prepend invisible view of saved location till first row
1244                    final int index = mFirstVisiblePos - 1;
1245                    final int row = mGrid.getLocation(index).row;
1246                    mGridProvider.createItem(index, row, false);
1247                    if (row == 0) {
1248                        return false;
1249                    }
1250                } else {
1251                    mGrid.prependItems(mScrollOffsetPrimary);
1252                    return false;
1253                }
1254            } else {
1255                return true;
1256            }
1257        }
1258    }
1259
1260    private void prependVisibleItems() {
1261        while (needsPrependVisibleItem()) {
1262            if (prependOneVisibleItem()) {
1263                break;
1264            }
1265        }
1266    }
1267
1268    private void removeChildAt(int position) {
1269        View v = findViewByPosition(position);
1270        if (v != null) {
1271            if (DEBUG) {
1272                Log.d(getTag(), "removeAndRecycleViewAt " + position);
1273            }
1274            mChildrenStates.saveOffscreenView(v, position);
1275            removeAndRecycleView(v, mRecycler);
1276        }
1277    }
1278
1279    private void removeInvisibleViewsAtEnd() {
1280        if (!mPruneChild) {
1281            return;
1282        }
1283        boolean update = false;
1284        while(mLastVisiblePos > mFirstVisiblePos && mLastVisiblePos > mFocusPosition) {
1285            View view = findViewByPosition(mLastVisiblePos);
1286            if (getViewMin(view) > mSizePrimary) {
1287                removeChildAt(mLastVisiblePos);
1288                mLastVisiblePos--;
1289                update = true;
1290            } else {
1291                break;
1292            }
1293        }
1294        if (update) {
1295            updateRowsMinMax();
1296        }
1297    }
1298
1299    private void removeInvisibleViewsAtFront() {
1300        if (!mPruneChild) {
1301            return;
1302        }
1303        boolean update = false;
1304        while(mLastVisiblePos > mFirstVisiblePos && mFirstVisiblePos < mFocusPosition) {
1305            View view = findViewByPosition(mFirstVisiblePos);
1306            if (getViewMax(view) < 0) {
1307                removeChildAt(mFirstVisiblePos);
1308                mFirstVisiblePos++;
1309                update = true;
1310            } else {
1311                break;
1312            }
1313        }
1314        if (update) {
1315            updateRowsMinMax();
1316        }
1317    }
1318
1319    private void updateRowsMinMax() {
1320        if (mFirstVisiblePos < 0) {
1321            return;
1322        }
1323        for (int i = 0; i < mNumRows; i++) {
1324            mRows[i].low = Integer.MAX_VALUE;
1325            mRows[i].high = Integer.MIN_VALUE;
1326        }
1327        for (int i = mFirstVisiblePos; i <= mLastVisiblePos; i++) {
1328            View view = findViewByPosition(i);
1329            int row = mGrid.getLocation(i).row;
1330            int low = getViewMin(view) + mScrollOffsetPrimary;
1331            if (low < mRows[row].low) {
1332                mRows[row].low = low;
1333            }
1334            int high = getViewMax(view) + mScrollOffsetPrimary;
1335            if (high > mRows[row].high) {
1336                mRows[row].high = high;
1337            }
1338        }
1339    }
1340
1341    // Fast layout when there is no structure change, adapter change, etc.
1342    protected void fastRelayout(boolean scrollToFocus) {
1343        initScrollController();
1344
1345        List<Integer>[] rows = mGrid.getItemPositionsInRows(mFirstVisiblePos, mLastVisiblePos);
1346
1347        // relayout and repositioning views on each row
1348        for (int i = 0; i < mNumRows; i++) {
1349            List<Integer> row = rows[i];
1350            final int startSecondary = getRowStartSecondary(i) - mScrollOffsetSecondary;
1351            for (int j = 0, size = row.size(); j < size; j++) {
1352                final int position = row.get(j);
1353                final View view = findViewByPosition(position);
1354                int primaryDelta, start, end;
1355
1356                if (mOrientation == HORIZONTAL) {
1357                    final int primarySize = view.getMeasuredWidth();
1358                    if (view.isLayoutRequested()) {
1359                        measureChild(view);
1360                    }
1361                    start = getViewMin(view);
1362                    end = start + view.getMeasuredWidth();
1363                    primaryDelta = view.getMeasuredWidth() - primarySize;
1364                    if (primaryDelta != 0) {
1365                        for (int k = j + 1; k < size; k++) {
1366                            findViewByPosition(row.get(k)).offsetLeftAndRight(primaryDelta);
1367                        }
1368                    }
1369                } else {
1370                    final int primarySize = view.getMeasuredHeight();
1371                    if (view.isLayoutRequested()) {
1372                        measureChild(view);
1373                    }
1374                    start = getViewMin(view);
1375                    end = start + view.getMeasuredHeight();
1376                    primaryDelta = view.getMeasuredHeight() - primarySize;
1377                    if (primaryDelta != 0) {
1378                        for (int k = j + 1; k < size; k++) {
1379                            findViewByPosition(row.get(k)).offsetTopAndBottom(primaryDelta);
1380                        }
1381                    }
1382                }
1383                layoutChild(i, view, start, end, startSecondary);
1384            }
1385        }
1386
1387        updateRowsMinMax();
1388        appendVisibleItems();
1389        prependVisibleItems();
1390
1391        updateRowsMinMax();
1392        updateScrollMin();
1393        updateScrollMax();
1394        updateScrollSecondAxis();
1395
1396        if (scrollToFocus) {
1397            View focusView = findViewByPosition(mFocusPosition == NO_POSITION ? 0 : mFocusPosition);
1398            scrollToView(focusView, false);
1399        }
1400    }
1401
1402    public void removeAndRecycleAllViews(RecyclerView.Recycler recycler) {
1403        if (DEBUG) Log.v(TAG, "removeAndRecycleAllViews " + getChildCount());
1404        for (int i = getChildCount() - 1; i >= 0; i--) {
1405            removeAndRecycleViewAt(i, recycler);
1406        }
1407    }
1408
1409    // Lays out items based on the current scroll position
1410    @Override
1411    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
1412        if (DEBUG) {
1413            Log.v(getTag(), "layoutChildren start numRows " + mNumRows + " mScrollOffsetSecondary "
1414                    + mScrollOffsetSecondary + " mScrollOffsetPrimary " + mScrollOffsetPrimary
1415                    + " inPreLayout " + state.isPreLayout()
1416                    + " didStructureChange " + state.didStructureChange()
1417                    + " mForceFullLayout " + mForceFullLayout);
1418            Log.v(getTag(), "width " + getWidth() + " height " + getHeight());
1419        }
1420
1421        if (mNumRows == 0) {
1422            // haven't done measure yet
1423            return;
1424        }
1425        final int itemCount = state.getItemCount();
1426        if (itemCount < 0) {
1427            return;
1428        }
1429
1430        if (!mLayoutEnabled) {
1431            discardLayoutInfo();
1432            removeAndRecycleAllViews(recycler);
1433            return;
1434        }
1435        mInLayout = true;
1436
1437        if (mLoadingState != null) {
1438            mFocusPosition = mLoadingState.index;
1439            mFocusPositionOffset = 0;
1440            mChildrenStates.getChildStates().putAll(mLoadingState.childStates);
1441            mLoadingState = null;
1442        }
1443        final boolean scrollToFocus = !isSmoothScrolling()
1444                && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED;
1445        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
1446            mFocusPosition = mFocusPosition + mFocusPositionOffset;
1447            mFocusPositionOffset = 0;
1448        }
1449        saveContext(recycler, state);
1450        // Track the old focus view so we can adjust our system scroll position
1451        // so that any scroll animations happening now will remain valid.
1452        // We must use same delta in Pre Layout (if prelayout exists) and second layout.
1453        // So we cache the deltas in PreLayout and use it in second layout.
1454        int delta = 0, deltaSecondary = 0;
1455        if (mFocusPosition != NO_POSITION && scrollToFocus) {
1456            // FIXME: we should get the remaining scroll animation offset from RecyclerView
1457            View focusView = findViewByPosition(mFocusPosition);
1458            if (focusView != null) {
1459                delta = mWindowAlignment.mainAxis().getSystemScrollPos(mScrollOffsetPrimary
1460                        + getViewCenter(focusView), false, false) - mScrollOffsetPrimary;
1461                deltaSecondary = mWindowAlignment.secondAxis().getSystemScrollPos(
1462                        mScrollOffsetSecondary + getViewCenterSecondary(focusView),
1463                        false, false) - mScrollOffsetSecondary;
1464            }
1465        }
1466
1467        final boolean hasDoneFirstLayout = hasDoneFirstLayout();
1468        int savedFocusPos = mFocusPosition;
1469        boolean fastRelayout = false;
1470        if (!mState.didStructureChange() && !mForceFullLayout && hasDoneFirstLayout) {
1471            fastRelayout = true;
1472            fastRelayout(scrollToFocus);
1473        } else {
1474            boolean hadFocus = mBaseGridView.hasFocus();
1475
1476            int newFocusPosition = init(mFocusPosition);
1477            if (DEBUG) {
1478                Log.v(getTag(), "mFocusPosition " + mFocusPosition + " newFocusPosition "
1479                    + newFocusPosition);
1480            }
1481
1482            // depending on result of init(), either recreating everything
1483            // or try to reuse the row start positions near mFocusPosition
1484            if (mGrid.getSize() == 0) {
1485                // this is a fresh creating all items, starting from
1486                // mFocusPosition with a estimated row index.
1487                mGrid.setStart(newFocusPosition, StaggeredGrid.START_DEFAULT);
1488
1489                // Can't track the old focus view
1490                delta = deltaSecondary = 0;
1491
1492            } else {
1493                // mGrid remembers Locations for the column that
1494                // contains mFocusePosition and also mRows remembers start
1495                // positions of each row.
1496                // Manually re-create child views for that column
1497                int firstIndex = mGrid.getFirstIndex();
1498                int lastIndex = mGrid.getLastIndex();
1499                for (int i = firstIndex; i <= lastIndex; i++) {
1500                    mGridProvider.createItem(i, mGrid.getLocation(i).row, true);
1501                }
1502            }
1503            // add visible views at end until reach the end of window
1504            appendVisibleItems();
1505            // add visible views at front until reach the start of window
1506            prependVisibleItems();
1507            // multiple rounds: scrollToView of first round may drag first/last child into
1508            // "visible window" and we update scrollMin/scrollMax then run second scrollToView
1509            int oldFirstVisible;
1510            int oldLastVisible;
1511            do {
1512                updateScrollMin();
1513                updateScrollMax();
1514                oldFirstVisible = mFirstVisiblePos;
1515                oldLastVisible = mLastVisiblePos;
1516                View focusView = findViewByPosition(newFocusPosition);
1517                // we need force to initialize the child view's position
1518                scrollToView(focusView, false);
1519                if (focusView != null && hadFocus) {
1520                    focusView.requestFocus();
1521                }
1522                appendVisibleItems();
1523                prependVisibleItems();
1524                removeInvisibleViewsAtFront();
1525                removeInvisibleViewsAtEnd();
1526            } while (mFirstVisiblePos != oldFirstVisible || mLastVisiblePos != oldLastVisible);
1527        }
1528        mForceFullLayout = false;
1529
1530        if (scrollToFocus) {
1531            scrollDirectionPrimary(-delta);
1532            scrollDirectionSecondary(-deltaSecondary);
1533        }
1534        appendVisibleItems();
1535        prependVisibleItems();
1536        removeInvisibleViewsAtFront();
1537        removeInvisibleViewsAtEnd();
1538
1539        if (DEBUG) {
1540            StringWriter sw = new StringWriter();
1541            PrintWriter pw = new PrintWriter(sw);
1542            mGrid.debugPrint(pw);
1543            Log.d(getTag(), sw.toString());
1544        }
1545
1546        if (mRowSecondarySizeRefresh) {
1547            mRowSecondarySizeRefresh = false;
1548        } else {
1549            updateRowSecondarySizeRefresh();
1550        }
1551
1552        if (!fastRelayout || mFocusPosition != savedFocusPos) {
1553            dispatchChildSelected();
1554        }
1555        mInLayout = false;
1556        leaveContext();
1557        if (DEBUG) Log.v(getTag(), "layoutChildren end");
1558    }
1559
1560    private void offsetChildrenSecondary(int increment) {
1561        final int childCount = getChildCount();
1562        if (mOrientation == HORIZONTAL) {
1563            for (int i = 0; i < childCount; i++) {
1564                getChildAt(i).offsetTopAndBottom(increment);
1565            }
1566        } else {
1567            for (int i = 0; i < childCount; i++) {
1568                getChildAt(i).offsetLeftAndRight(increment);
1569            }
1570        }
1571    }
1572
1573    private void offsetChildrenPrimary(int increment) {
1574        final int childCount = getChildCount();
1575        if (mOrientation == VERTICAL) {
1576            for (int i = 0; i < childCount; i++) {
1577                getChildAt(i).offsetTopAndBottom(increment);
1578            }
1579        } else {
1580            for (int i = 0; i < childCount; i++) {
1581                getChildAt(i).offsetLeftAndRight(increment);
1582            }
1583        }
1584    }
1585
1586    @Override
1587    public int scrollHorizontallyBy(int dx, Recycler recycler, RecyclerView.State state) {
1588        if (DEBUG) Log.v(getTag(), "scrollHorizontallyBy " + dx);
1589        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1590            return 0;
1591        }
1592        saveContext(recycler, state);
1593        int result;
1594        if (mOrientation == HORIZONTAL) {
1595            result = scrollDirectionPrimary(dx);
1596        } else {
1597            result = scrollDirectionSecondary(dx);
1598        }
1599        leaveContext();
1600        return result;
1601    }
1602
1603    @Override
1604    public int scrollVerticallyBy(int dy, Recycler recycler, RecyclerView.State state) {
1605        if (DEBUG) Log.v(getTag(), "scrollVerticallyBy " + dy);
1606        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1607            return 0;
1608        }
1609        saveContext(recycler, state);
1610        int result;
1611        if (mOrientation == VERTICAL) {
1612            result = scrollDirectionPrimary(dy);
1613        } else {
1614            result = scrollDirectionSecondary(dy);
1615        }
1616        leaveContext();
1617        return result;
1618    }
1619
1620    // scroll in main direction may add/prune views
1621    private int scrollDirectionPrimary(int da) {
1622        if (da > 0) {
1623            if (!mWindowAlignment.mainAxis().isMaxUnknown()) {
1624                int maxScroll = mWindowAlignment.mainAxis().getMaxScroll();
1625                if (mScrollOffsetPrimary + da > maxScroll) {
1626                    da = maxScroll - mScrollOffsetPrimary;
1627                }
1628            }
1629        } else if (da < 0) {
1630            if (!mWindowAlignment.mainAxis().isMinUnknown()) {
1631                int minScroll = mWindowAlignment.mainAxis().getMinScroll();
1632                if (mScrollOffsetPrimary + da < minScroll) {
1633                    da = minScroll - mScrollOffsetPrimary;
1634                }
1635            }
1636        }
1637        if (da == 0) {
1638            return 0;
1639        }
1640        offsetChildrenPrimary(-da);
1641        mScrollOffsetPrimary += da;
1642        if (mInLayout) {
1643            return da;
1644        }
1645
1646        int childCount = getChildCount();
1647        boolean updated;
1648
1649        if (da > 0) {
1650            appendVisibleItems();
1651        } else if (da < 0) {
1652            prependVisibleItems();
1653        }
1654        updated = getChildCount() > childCount;
1655        childCount = getChildCount();
1656
1657        if (da > 0) {
1658            removeInvisibleViewsAtFront();
1659        } else if (da < 0) {
1660            removeInvisibleViewsAtEnd();
1661        }
1662        updated |= getChildCount() < childCount;
1663
1664        if (updated) {
1665            updateRowSecondarySizeRefresh();
1666        }
1667
1668        mBaseGridView.invalidate();
1669        return da;
1670    }
1671
1672    // scroll in second direction will not add/prune views
1673    private int scrollDirectionSecondary(int dy) {
1674        if (dy == 0) {
1675            return 0;
1676        }
1677        offsetChildrenSecondary(-dy);
1678        mScrollOffsetSecondary += dy;
1679        mBaseGridView.invalidate();
1680        return dy;
1681    }
1682
1683    private void updateScrollMax() {
1684        if (mLastVisiblePos < 0) {
1685            return;
1686        }
1687        final boolean lastAvailable = mLastVisiblePos == mState.getItemCount() - 1;
1688        final boolean maxUnknown = mWindowAlignment.mainAxis().isMaxUnknown();
1689        if (!lastAvailable && maxUnknown) {
1690            return;
1691        }
1692        int maxEdge = Integer.MIN_VALUE;
1693        int rowIndex = -1;
1694        for (int i = 0; i < mRows.length; i++) {
1695            if (mRows[i].high > maxEdge) {
1696                maxEdge = mRows[i].high;
1697                rowIndex = i;
1698            }
1699        }
1700        int maxScroll = Integer.MAX_VALUE;
1701        for (int i = mLastVisiblePos; i >= mFirstVisiblePos; i--) {
1702            StaggeredGrid.Location location = mGrid.getLocation(i);
1703            if (location != null && location.row == rowIndex) {
1704                int savedMaxEdge = mWindowAlignment.mainAxis().getMaxEdge();
1705                mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1706                maxScroll = getPrimarySystemScrollPosition(findViewByPosition(i));
1707                mWindowAlignment.mainAxis().setMaxEdge(savedMaxEdge);
1708                break;
1709            }
1710        }
1711        if (lastAvailable) {
1712            mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1713            mWindowAlignment.mainAxis().setMaxScroll(maxScroll);
1714            if (DEBUG) Log.v(getTag(), "updating scroll maxEdge to " + maxEdge +
1715                    " scrollMax to " + maxScroll);
1716        } else {
1717            // the maxScroll for currently last visible item is larger,
1718            // so we must invalidate the max scroll value.
1719            if (maxScroll > mWindowAlignment.mainAxis().getMaxScroll()) {
1720                mWindowAlignment.mainAxis().invalidateScrollMax();
1721                if (DEBUG) Log.v(getTag(), "Invalidate scrollMax since it should be "
1722                        + "greater than " + maxScroll);
1723            }
1724        }
1725    }
1726
1727    private void updateScrollMin() {
1728        if (mFirstVisiblePos < 0) {
1729            return;
1730        }
1731        final boolean firstAvailable = mFirstVisiblePos == 0;
1732        final boolean minUnknown = mWindowAlignment.mainAxis().isMinUnknown();
1733        if (!firstAvailable && minUnknown) {
1734            return;
1735        }
1736        int minEdge = Integer.MAX_VALUE;
1737        int rowIndex = -1;
1738        for (int i = 0; i < mRows.length; i++) {
1739            if (mRows[i].low < minEdge) {
1740                minEdge = mRows[i].low;
1741                rowIndex = i;
1742            }
1743        }
1744        int minScroll = Integer.MIN_VALUE;
1745        for (int i = mFirstVisiblePos; i <= mLastVisiblePos; i++) {
1746            StaggeredGrid.Location location = mGrid.getLocation(i);
1747            if (location != null && location.row == rowIndex) {
1748                int savedMinEdge = mWindowAlignment.mainAxis().getMinEdge();
1749                mWindowAlignment.mainAxis().setMinEdge(minEdge);
1750                minScroll = getPrimarySystemScrollPosition(findViewByPosition(i));
1751                mWindowAlignment.mainAxis().setMinEdge(savedMinEdge);
1752                break;
1753            }
1754        }
1755        if (firstAvailable) {
1756            mWindowAlignment.mainAxis().setMinEdge(minEdge);
1757            mWindowAlignment.mainAxis().setMinScroll(minScroll);
1758            if (DEBUG) Log.v(getTag(), "updating scroll minEdge to " + minEdge +
1759                    " scrollMin to " + minScroll);
1760        } else {
1761            // the minScroll for currently first visible item is smaller,
1762            // so we must invalidate the min scroll value.
1763            if (minScroll < mWindowAlignment.mainAxis().getMinScroll()) {
1764                mWindowAlignment.mainAxis().invalidateScrollMin();
1765                if (DEBUG) Log.v(getTag(), "Invalidate scrollMin, since it should be "
1766                        + "less than " + minScroll);
1767            }
1768        }
1769    }
1770
1771    private void updateScrollSecondAxis() {
1772        mWindowAlignment.secondAxis().setMinEdge(0);
1773        mWindowAlignment.secondAxis().setMaxEdge(getSizeSecondary());
1774    }
1775
1776    private void initScrollController() {
1777        // mScrollOffsetPrimary and mScrollOffsetSecondary includes the padding.
1778        // e.g. when topPadding is 16 for horizontal grid view,  the initial
1779        // mScrollOffsetSecondary is -16.  fastLayout() put views based on offsets(not padding),
1780        // when padding changes to 20,  we also need update mScrollOffsetSecondary to -20 before
1781        // fastLayout() is performed
1782        int paddingPrimaryDiff, paddingSecondaryDiff;
1783        if (mOrientation == HORIZONTAL) {
1784            paddingPrimaryDiff = getPaddingLeft() - mWindowAlignment.horizontal.getPaddingLow();
1785            paddingSecondaryDiff = getPaddingTop() - mWindowAlignment.vertical.getPaddingLow();
1786        } else {
1787            paddingPrimaryDiff = getPaddingTop() - mWindowAlignment.vertical.getPaddingLow();
1788            paddingSecondaryDiff = getPaddingLeft() - mWindowAlignment.horizontal.getPaddingLow();
1789        }
1790        mScrollOffsetPrimary -= paddingPrimaryDiff;
1791        mScrollOffsetSecondary -= paddingSecondaryDiff;
1792
1793        mWindowAlignment.horizontal.setSize(getWidth());
1794        mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight());
1795        mWindowAlignment.vertical.setSize(getHeight());
1796        mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom());
1797        mSizePrimary = mWindowAlignment.mainAxis().getSize();
1798
1799        if (DEBUG) {
1800            Log.v(getTag(), "initScrollController mSizePrimary " + mSizePrimary
1801                    + " mWindowAlignment " + mWindowAlignment);
1802        }
1803    }
1804
1805    public void setSelection(RecyclerView parent, int position) {
1806        setSelection(parent, position, false);
1807    }
1808
1809    public void setSelectionSmooth(RecyclerView parent, int position) {
1810        setSelection(parent, position, true);
1811    }
1812
1813    public int getSelection() {
1814        return mFocusPosition;
1815    }
1816
1817    public void setSelection(RecyclerView parent, int position, boolean smooth) {
1818        if (mFocusPosition == position) {
1819            return;
1820        }
1821        View view = findViewByPosition(position);
1822        if (view != null) {
1823            mInSelection = true;
1824            scrollToView(view, smooth);
1825            mInSelection = false;
1826        } else {
1827            mFocusPosition = position;
1828            mFocusPositionOffset = 0;
1829            if (!mLayoutEnabled) {
1830                return;
1831            }
1832            if (smooth) {
1833                if (!hasDoneFirstLayout()) {
1834                    Log.w(getTag(), "setSelectionSmooth should " +
1835                            "not be called before first layout pass");
1836                    return;
1837                }
1838                LinearSmoothScroller linearSmoothScroller =
1839                        new LinearSmoothScroller(parent.getContext()) {
1840                    @Override
1841                    public PointF computeScrollVectorForPosition(int targetPosition) {
1842                        if (getChildCount() == 0) {
1843                            return null;
1844                        }
1845                        final int firstChildPos = getPosition(getChildAt(0));
1846                        final int direction = targetPosition < firstChildPos ? -1 : 1;
1847                        if (mOrientation == HORIZONTAL) {
1848                            return new PointF(direction, 0);
1849                        } else {
1850                            return new PointF(0, direction);
1851                        }
1852                    }
1853                    @Override
1854                    protected void onTargetFound(View targetView,
1855                            RecyclerView.State state, Action action) {
1856                        if (hasFocus()) {
1857                            targetView.requestFocus();
1858                        }
1859                        dispatchChildSelected();
1860                        if (getScrollPosition(targetView, mTempDeltas)) {
1861                            int dx, dy;
1862                            if (mOrientation == HORIZONTAL) {
1863                                dx = mTempDeltas[0];
1864                                dy = mTempDeltas[1];
1865                            } else {
1866                                dx = mTempDeltas[1];
1867                                dy = mTempDeltas[0];
1868                            }
1869                            final int distance = (int) Math.sqrt(dx * dx + dy * dy);
1870                            final int time = calculateTimeForDeceleration(distance);
1871                            action.update(dx, dy, time, mDecelerateInterpolator);
1872                        }
1873                    }
1874                };
1875                linearSmoothScroller.setTargetPosition(position);
1876                startSmoothScroll(linearSmoothScroller);
1877            } else {
1878                mForceFullLayout = true;
1879                parent.requestLayout();
1880            }
1881        }
1882    }
1883
1884    @Override
1885    public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
1886        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
1887            int pos = mFocusPosition + mFocusPositionOffset;
1888            if (positionStart <= pos) {
1889                mFocusPositionOffset += itemCount;
1890            }
1891        }
1892    }
1893
1894    @Override
1895    public void onItemsChanged(RecyclerView recyclerView) {
1896        mFocusPositionOffset = 0;
1897    }
1898
1899    @Override
1900    public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) {
1901        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
1902            int pos = mFocusPosition + mFocusPositionOffset;
1903            if (positionStart <= pos) {
1904                if (positionStart + itemCount > pos) {
1905                    // stop updating offset after the focus item was removed
1906                    mFocusPositionOffset = Integer.MIN_VALUE;
1907                } else {
1908                    mFocusPositionOffset -= itemCount;
1909                }
1910            }
1911        }
1912    }
1913
1914    public void onItemsMoved(RecyclerView recyclerView, int fromPosition, int toPosition,
1915            int itemCount) {
1916        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
1917            int pos = mFocusPosition + mFocusPositionOffset;
1918            if (fromPosition <= pos && pos < fromPosition + itemCount) {
1919                // moved items include focused position
1920                mFocusPositionOffset += toPosition - fromPosition;
1921            } else if (fromPosition < pos && toPosition > pos - itemCount) {
1922                // move items before focus position to after focused position
1923                mFocusPositionOffset -= itemCount;
1924            } else if (fromPosition > pos && toPosition < pos) {
1925                // move items after focus position to before focused position
1926                mFocusPositionOffset += itemCount;
1927            }
1928        }
1929    }
1930
1931    @Override
1932    public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) {
1933        if (mFocusSearchDisabled) {
1934            return true;
1935        }
1936        if (!mInLayout && !mInSelection) {
1937            scrollToView(child, true);
1938        }
1939        return true;
1940    }
1941
1942    @Override
1943    public boolean requestChildRectangleOnScreen(RecyclerView parent, View view, Rect rect,
1944            boolean immediate) {
1945        if (DEBUG) Log.v(getTag(), "requestChildRectangleOnScreen " + view + " " + rect);
1946        return false;
1947    }
1948
1949    int getScrollOffsetX() {
1950        return mOrientation == HORIZONTAL ? mScrollOffsetPrimary : mScrollOffsetSecondary;
1951    }
1952
1953    int getScrollOffsetY() {
1954        return mOrientation == HORIZONTAL ? mScrollOffsetSecondary : mScrollOffsetPrimary;
1955    }
1956
1957    public void getViewSelectedOffsets(View view, int[] offsets) {
1958        if (mOrientation == HORIZONTAL) {
1959            offsets[0] = getPrimarySystemScrollPosition(view) - mScrollOffsetPrimary;
1960            offsets[1] = getSecondarySystemScrollPosition(view) - mScrollOffsetSecondary;
1961        } else {
1962            offsets[1] = getPrimarySystemScrollPosition(view) - mScrollOffsetPrimary;
1963            offsets[0] = getSecondarySystemScrollPosition(view) - mScrollOffsetSecondary;
1964        }
1965    }
1966
1967    private int getPrimarySystemScrollPosition(View view) {
1968        int viewCenterPrimary = mScrollOffsetPrimary + getViewCenter(view);
1969        int pos = getPositionByView(view);
1970        StaggeredGrid.Location location = mGrid.getLocation(pos);
1971        final int row = location.row;
1972        boolean isFirst = mFirstVisiblePos == 0;
1973        // TODO: change to use State object in onRequestChildFocus()
1974        boolean isLast = mLastVisiblePos == (mState == null ?
1975                getItemCount() : mState.getItemCount()) - 1;
1976        if (isFirst || isLast) {
1977            for (int i = getChildCount() - 1; i >= 0; i--) {
1978                int position = getPositionByIndex(i);
1979                StaggeredGrid.Location loc = mGrid.getLocation(position);
1980                if (loc != null && loc.row == row) {
1981                    if (position < pos) {
1982                        isFirst = false;
1983                    } else if (position > pos) {
1984                        isLast = false;
1985                    }
1986                }
1987            }
1988        }
1989        return mWindowAlignment.mainAxis().getSystemScrollPos(viewCenterPrimary, isFirst, isLast);
1990    }
1991
1992    private int getSecondarySystemScrollPosition(View view) {
1993        int viewCenterSecondary = mScrollOffsetSecondary + getViewCenterSecondary(view);
1994        int pos = getPositionByView(view);
1995        StaggeredGrid.Location location = mGrid.getLocation(pos);
1996        final int row = location.row;
1997        boolean isFirst = row == 0;
1998        boolean isLast = row == mGrid.getNumRows() - 1;
1999        return mWindowAlignment.secondAxis().getSystemScrollPos(viewCenterSecondary,
2000                isFirst, isLast);
2001    }
2002
2003    /**
2004     * Scroll to a given child view and change mFocusPosition.
2005     */
2006    private void scrollToView(View view, boolean smooth) {
2007        int newFocusPosition = getPositionByView(view);
2008        if (newFocusPosition != mFocusPosition) {
2009            mFocusPosition = newFocusPosition;
2010            mFocusPositionOffset = 0;
2011            if (!mInLayout) {
2012                dispatchChildSelected();
2013            }
2014        }
2015        if (mBaseGridView.isChildrenDrawingOrderEnabledInternal()) {
2016            mBaseGridView.invalidate();
2017        }
2018        if (view == null) {
2019            return;
2020        }
2021        if (!view.hasFocus() && mBaseGridView.hasFocus()) {
2022            // transfer focus to the child if it does not have focus yet (e.g. triggered
2023            // by setSelection())
2024            view.requestFocus();
2025        }
2026        if (!mScrollEnabled) {
2027            return;
2028        }
2029        if (getScrollPosition(view, mTempDeltas)) {
2030            scrollGrid(mTempDeltas[0], mTempDeltas[1], smooth);
2031        }
2032    }
2033
2034    private boolean getScrollPosition(View view, int[] deltas) {
2035        switch (mFocusScrollStrategy) {
2036        case BaseGridView.FOCUS_SCROLL_ALIGNED:
2037        default:
2038            return getAlignedPosition(view, deltas);
2039        case BaseGridView.FOCUS_SCROLL_ITEM:
2040        case BaseGridView.FOCUS_SCROLL_PAGE:
2041            return getNoneAlignedPosition(view, deltas);
2042        }
2043    }
2044
2045    private boolean getNoneAlignedPosition(View view, int[] deltas) {
2046        int pos = getPositionByView(view);
2047        int viewMin = getViewMin(view);
2048        int viewMax = getViewMax(view);
2049        // we either align "firstView" to left/top padding edge
2050        // or align "lastView" to right/bottom padding edge
2051        View firstView = null;
2052        View lastView = null;
2053        int paddingLow = mWindowAlignment.mainAxis().getPaddingLow();
2054        int clientSize = mWindowAlignment.mainAxis().getClientSize();
2055        final int row = mGrid.getLocation(pos).row;
2056        if (viewMin < paddingLow) {
2057            // view enters low padding area:
2058            firstView = view;
2059            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
2060                // scroll one "page" left/top,
2061                // align first visible item of the "page" at the low padding edge.
2062                while (!prependOneVisibleItem()) {
2063                    List<Integer> positions =
2064                            mGrid.getItemPositionsInRows(mFirstVisiblePos, pos)[row];
2065                    firstView = findViewByPosition(positions.get(0));
2066                    if (viewMax - getViewMin(firstView) > clientSize) {
2067                        if (positions.size() > 1) {
2068                            firstView = findViewByPosition(positions.get(1));
2069                        }
2070                        break;
2071                    }
2072                }
2073            }
2074        } else if (viewMax > clientSize + paddingLow) {
2075            // view enters high padding area:
2076            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
2077                // scroll whole one page right/bottom, align view at the low padding edge.
2078                firstView = view;
2079                do {
2080                    List<Integer> positions =
2081                            mGrid.getItemPositionsInRows(pos, mLastVisiblePos)[row];
2082                    lastView = findViewByPosition(positions.get(positions.size() - 1));
2083                    if (getViewMax(lastView) - viewMin > clientSize) {
2084                        lastView = null;
2085                        break;
2086                    }
2087                } while (!appendOneVisibleItem());
2088                if (lastView != null) {
2089                    // however if we reached end,  we should align last view.
2090                    firstView = null;
2091                }
2092            } else {
2093                lastView = view;
2094            }
2095        }
2096        int scrollPrimary = 0;
2097        int scrollSecondary = 0;
2098        if (firstView != null) {
2099            scrollPrimary = getViewMin(firstView) - paddingLow;
2100        } else if (lastView != null) {
2101            scrollPrimary = getViewMax(lastView) - (paddingLow + clientSize);
2102        }
2103        View secondaryAlignedView;
2104        if (firstView != null) {
2105            secondaryAlignedView = firstView;
2106        } else if (lastView != null) {
2107            secondaryAlignedView = lastView;
2108        } else {
2109            secondaryAlignedView = view;
2110        }
2111        scrollSecondary = getSecondarySystemScrollPosition(secondaryAlignedView);
2112        scrollSecondary -= mScrollOffsetSecondary;
2113        if (scrollPrimary != 0 || scrollSecondary != 0) {
2114            deltas[0] = scrollPrimary;
2115            deltas[1] = scrollSecondary;
2116            return true;
2117        }
2118        return false;
2119    }
2120
2121    private boolean getAlignedPosition(View view, int[] deltas) {
2122        int scrollPrimary = getPrimarySystemScrollPosition(view);
2123        int scrollSecondary = getSecondarySystemScrollPosition(view);
2124        if (DEBUG) {
2125            Log.v(getTag(), "getAlignedPosition " + scrollPrimary + " " + scrollSecondary
2126                    +" " + mWindowAlignment);
2127        }
2128        scrollPrimary -= mScrollOffsetPrimary;
2129        scrollSecondary -= mScrollOffsetSecondary;
2130        if (scrollPrimary != 0 || scrollSecondary != 0) {
2131            deltas[0] = scrollPrimary;
2132            deltas[1] = scrollSecondary;
2133            return true;
2134        }
2135        return false;
2136    }
2137
2138    private void scrollGrid(int scrollPrimary, int scrollSecondary, boolean smooth) {
2139        if (mInLayout) {
2140            scrollDirectionPrimary(scrollPrimary);
2141            scrollDirectionSecondary(scrollSecondary);
2142        } else {
2143            int scrollX;
2144            int scrollY;
2145            if (mOrientation == HORIZONTAL) {
2146                scrollX = scrollPrimary;
2147                scrollY = scrollSecondary;
2148            } else {
2149                scrollX = scrollSecondary;
2150                scrollY = scrollPrimary;
2151            }
2152            if (smooth) {
2153                mBaseGridView.smoothScrollBy(scrollX, scrollY);
2154            } else {
2155                mBaseGridView.scrollBy(scrollX, scrollY);
2156            }
2157        }
2158    }
2159
2160    public void setPruneChild(boolean pruneChild) {
2161        if (mPruneChild != pruneChild) {
2162            mPruneChild = pruneChild;
2163            if (mPruneChild) {
2164                requestLayout();
2165            }
2166        }
2167    }
2168
2169    public boolean getPruneChild() {
2170        return mPruneChild;
2171    }
2172
2173    public void setScrollEnabled(boolean scrollEnabled) {
2174        if (mScrollEnabled != scrollEnabled) {
2175            mScrollEnabled = scrollEnabled;
2176            if (mScrollEnabled && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
2177                View focusView = findViewByPosition(mFocusPosition == NO_POSITION ? 0 :
2178                    mFocusPosition);
2179                if (focusView != null) {
2180                    scrollToView(focusView, true);
2181                }
2182            }
2183        }
2184    }
2185
2186    public boolean isScrollEnabled() {
2187        return mScrollEnabled;
2188    }
2189
2190    private int findImmediateChildIndex(View view) {
2191        while (view != null && view != mBaseGridView) {
2192            int index = mBaseGridView.indexOfChild(view);
2193            if (index >= 0) {
2194                return index;
2195            }
2196            view = (View) view.getParent();
2197        }
2198        return NO_POSITION;
2199    }
2200
2201    void setFocusSearchDisabled(boolean disabled) {
2202        mFocusSearchDisabled = disabled;
2203    }
2204
2205    boolean isFocusSearchDisabled() {
2206        return mFocusSearchDisabled;
2207    }
2208
2209    @Override
2210    public View onInterceptFocusSearch(View focused, int direction) {
2211        if (mFocusSearchDisabled) {
2212            return focused;
2213        }
2214        return null;
2215    }
2216
2217    boolean hasPreviousViewInSameRow(int pos) {
2218        if (mGrid == null || pos == NO_POSITION) {
2219            return false;
2220        }
2221        if (mFirstVisiblePos > 0) {
2222            return true;
2223        }
2224        final int focusedRow = mGrid.getLocation(pos).row;
2225        for (int i = getChildCount() - 1; i >= 0; i--) {
2226            int position = getPositionByIndex(i);
2227            StaggeredGrid.Location loc = mGrid.getLocation(position);
2228            if (loc != null && loc.row == focusedRow) {
2229                if (position < pos) {
2230                    return true;
2231                }
2232            }
2233        }
2234        return false;
2235    }
2236
2237    @Override
2238    public boolean onAddFocusables(RecyclerView recyclerView,
2239            ArrayList<View> views, int direction, int focusableMode) {
2240        if (mFocusSearchDisabled) {
2241            return true;
2242        }
2243        // If this viewgroup or one of its children currently has focus then we
2244        // consider our children for focus searching in main direction on the same row.
2245        // If this viewgroup has no focus and using focus align, we want the system
2246        // to ignore our children and pass focus to the viewgroup, which will pass
2247        // focus on to its children appropriately.
2248        // If this viewgroup has no focus and not using focus align, we want to
2249        // consider the child that does not overlap with padding area.
2250        if (recyclerView.hasFocus()) {
2251            final int movement = getMovement(direction);
2252            if (movement != PREV_ITEM && movement != NEXT_ITEM) {
2253                // Move on secondary direction uses default addFocusables().
2254                return false;
2255            }
2256            final View focused = recyclerView.findFocus();
2257            final int focusedPos = getPositionByIndex(findImmediateChildIndex(focused));
2258            // Add focusables of focused item.
2259            if (focusedPos != NO_POSITION) {
2260                findViewByPosition(focusedPos).addFocusables(views,  direction, focusableMode);
2261            }
2262            final int focusedRow = mGrid != null && focusedPos != NO_POSITION ?
2263                    mGrid.getLocation(focusedPos).row : NO_POSITION;
2264            // Add focusables of next neighbor of same row on the focus search direction.
2265            if (mGrid != null) {
2266                final int focusableCount = views.size();
2267                for (int i = 0, count = getChildCount(); i < count; i++) {
2268                    int index = movement == NEXT_ITEM ? i : count - 1 - i;
2269                    final View child = getChildAt(index);
2270                    if (child.getVisibility() != View.VISIBLE) {
2271                        continue;
2272                    }
2273                    int position = getPositionByIndex(index);
2274                    StaggeredGrid.Location loc = mGrid.getLocation(position);
2275                    if (focusedRow == NO_POSITION || (loc != null && loc.row == focusedRow)) {
2276                        if (focusedPos == NO_POSITION ||
2277                                (movement == NEXT_ITEM && position > focusedPos)
2278                                || (movement == PREV_ITEM && position < focusedPos)) {
2279                            child.addFocusables(views,  direction, focusableMode);
2280                            if (views.size() > focusableCount) {
2281                                break;
2282                            }
2283                        }
2284                    }
2285                }
2286            }
2287        } else {
2288            if (mFocusScrollStrategy != BaseGridView.FOCUS_SCROLL_ALIGNED) {
2289                // adding views not overlapping padding area to avoid scrolling in gaining focus
2290                int left = mWindowAlignment.mainAxis().getPaddingLow();
2291                int right = mWindowAlignment.mainAxis().getClientSize() + left;
2292                int focusableCount = views.size();
2293                for (int i = 0, count = getChildCount(); i < count; i++) {
2294                    View child = getChildAt(i);
2295                    if (child.getVisibility() == View.VISIBLE) {
2296                        if (getViewMin(child) >= left && getViewMax(child) <= right) {
2297                            child.addFocusables(views, direction, focusableMode);
2298                        }
2299                    }
2300                }
2301                // if we cannot find any, then just add all children.
2302                if (views.size() == focusableCount) {
2303                    for (int i = 0, count = getChildCount(); i < count; i++) {
2304                        View child = getChildAt(i);
2305                        if (child.getVisibility() == View.VISIBLE) {
2306                            child.addFocusables(views, direction, focusableMode);
2307                        }
2308                    }
2309                    if (views.size() != focusableCount) {
2310                        return true;
2311                    }
2312                } else {
2313                    return true;
2314                }
2315                // if still cannot find any, fall through and add itself
2316            }
2317            if (recyclerView.isFocusable()) {
2318                views.add(recyclerView);
2319            }
2320        }
2321        return true;
2322    }
2323
2324    @Override
2325    public View onFocusSearchFailed(View focused, int direction, Recycler recycler,
2326            RecyclerView.State state) {
2327        if (DEBUG) Log.v(getTag(), "onFocusSearchFailed direction " + direction);
2328
2329        View view = null;
2330        int movement = getMovement(direction);
2331        if (mNumRows == 1) {
2332            // for simple row, use LinearSmoothScroller to smooth animation.
2333            // It will stay at a fixed cap speed in continuous scroll.
2334            if (movement == NEXT_ITEM) {
2335                int newPos = mFocusPosition + mNumRows;
2336                if (newPos < getItemCount()) {
2337                    setSelectionSmooth(mBaseGridView, newPos);
2338                    view = focused;
2339                } else {
2340                    if (!mFocusOutEnd) {
2341                        view = focused;
2342                    }
2343                }
2344            } else if (movement == PREV_ITEM){
2345                int newPos = mFocusPosition - mNumRows;
2346                if (newPos >= 0) {
2347                    setSelectionSmooth(mBaseGridView, newPos);
2348                    view = focused;
2349                } else {
2350                    if (!mFocusOutFront) {
2351                        view = focused;
2352                    }
2353                }
2354            }
2355        } else if (mNumRows > 1) {
2356            // for possible staggered grid,  we need guarantee focus to same row/column.
2357            // TODO: we may also use LinearSmoothScroller.
2358            saveContext(recycler, state);
2359            final FocusFinder ff = FocusFinder.getInstance();
2360            if (movement == NEXT_ITEM) {
2361                while (view == null && !appendOneVisibleItem()) {
2362                    view = ff.findNextFocus(mBaseGridView, focused, direction);
2363                }
2364            } else if (movement == PREV_ITEM){
2365                while (view == null && !prependOneVisibleItem()) {
2366                    view = ff.findNextFocus(mBaseGridView, focused, direction);
2367                }
2368            }
2369            if (view == null) {
2370                // returning the same view to prevent focus lost when scrolling past the end of the list
2371                if (movement == PREV_ITEM) {
2372                    view = mFocusOutFront ? null : focused;
2373                } else if (movement == NEXT_ITEM){
2374                    view = mFocusOutEnd ? null : focused;
2375                }
2376            }
2377            leaveContext();
2378        }
2379        if (DEBUG) Log.v(getTag(), "returning view " + view);
2380        return view;
2381    }
2382
2383    boolean gridOnRequestFocusInDescendants(RecyclerView recyclerView, int direction,
2384            Rect previouslyFocusedRect) {
2385        switch (mFocusScrollStrategy) {
2386        case BaseGridView.FOCUS_SCROLL_ALIGNED:
2387        default:
2388            return gridOnRequestFocusInDescendantsAligned(recyclerView,
2389                    direction, previouslyFocusedRect);
2390        case BaseGridView.FOCUS_SCROLL_PAGE:
2391        case BaseGridView.FOCUS_SCROLL_ITEM:
2392            return gridOnRequestFocusInDescendantsUnaligned(recyclerView,
2393                    direction, previouslyFocusedRect);
2394        }
2395    }
2396
2397    private boolean gridOnRequestFocusInDescendantsAligned(RecyclerView recyclerView,
2398            int direction, Rect previouslyFocusedRect) {
2399        View view = findViewByPosition(mFocusPosition);
2400        if (view != null) {
2401            boolean result = view.requestFocus(direction, previouslyFocusedRect);
2402            if (!result && DEBUG) {
2403                Log.w(getTag(), "failed to request focus on " + view);
2404            }
2405            return result;
2406        }
2407        return false;
2408    }
2409
2410    private boolean gridOnRequestFocusInDescendantsUnaligned(RecyclerView recyclerView,
2411            int direction, Rect previouslyFocusedRect) {
2412        // focus to view not overlapping padding area to avoid scrolling in gaining focus
2413        int index;
2414        int increment;
2415        int end;
2416        int count = getChildCount();
2417        if ((direction & View.FOCUS_FORWARD) != 0) {
2418            index = 0;
2419            increment = 1;
2420            end = count;
2421        } else {
2422            index = count - 1;
2423            increment = -1;
2424            end = -1;
2425        }
2426        int left = mWindowAlignment.mainAxis().getPaddingLow();
2427        int right = mWindowAlignment.mainAxis().getClientSize() + left;
2428        for (int i = index; i != end; i += increment) {
2429            View child = getChildAt(i);
2430            if (child.getVisibility() == View.VISIBLE) {
2431                if (getViewMin(child) >= left && getViewMax(child) <= right) {
2432                    if (child.requestFocus(direction, previouslyFocusedRect)) {
2433                        return true;
2434                    }
2435                }
2436            }
2437        }
2438        return false;
2439    }
2440
2441    private final static int PREV_ITEM = 0;
2442    private final static int NEXT_ITEM = 1;
2443    private final static int PREV_ROW = 2;
2444    private final static int NEXT_ROW = 3;
2445
2446    private int getMovement(int direction) {
2447        int movement = View.FOCUS_LEFT;
2448
2449        if (mOrientation == HORIZONTAL) {
2450            switch(direction) {
2451                case View.FOCUS_LEFT:
2452                    movement = PREV_ITEM;
2453                    break;
2454                case View.FOCUS_RIGHT:
2455                    movement = NEXT_ITEM;
2456                    break;
2457                case View.FOCUS_UP:
2458                    movement = PREV_ROW;
2459                    break;
2460                case View.FOCUS_DOWN:
2461                    movement = NEXT_ROW;
2462                    break;
2463            }
2464         } else if (mOrientation == VERTICAL) {
2465             switch(direction) {
2466                 case View.FOCUS_LEFT:
2467                     movement = PREV_ROW;
2468                     break;
2469                 case View.FOCUS_RIGHT:
2470                     movement = NEXT_ROW;
2471                     break;
2472                 case View.FOCUS_UP:
2473                     movement = PREV_ITEM;
2474                     break;
2475                 case View.FOCUS_DOWN:
2476                     movement = NEXT_ITEM;
2477                     break;
2478             }
2479         }
2480
2481        return movement;
2482    }
2483
2484    int getChildDrawingOrder(RecyclerView recyclerView, int childCount, int i) {
2485        View view = findViewByPosition(mFocusPosition);
2486        if (view == null) {
2487            return i;
2488        }
2489        int focusIndex = recyclerView.indexOfChild(view);
2490        // supposely 0 1 2 3 4 5 6 7 8 9, 4 is the center item
2491        // drawing order is 0 1 2 3 9 8 7 6 5 4
2492        if (i < focusIndex) {
2493            return i;
2494        } else if (i < childCount - 1) {
2495            return focusIndex + childCount - 1 - i;
2496        } else {
2497            return focusIndex;
2498        }
2499    }
2500
2501    @Override
2502    public void onAdapterChanged(RecyclerView.Adapter oldAdapter,
2503            RecyclerView.Adapter newAdapter) {
2504        discardLayoutInfo();
2505        mFocusPosition = NO_POSITION;
2506        mFocusPositionOffset = 0;
2507        mLoadingState = null;
2508        mChildrenStates.clear();
2509        super.onAdapterChanged(oldAdapter, newAdapter);
2510    }
2511
2512    private void discardLayoutInfo() {
2513        mGrid = null;
2514        mRows = null;
2515        mRowSizeSecondary = null;
2516        mFirstVisiblePos = -1;
2517        mLastVisiblePos = -1;
2518        mRowSecondarySizeRefresh = false;
2519    }
2520
2521    public void setLayoutEnabled(boolean layoutEnabled) {
2522        if (mLayoutEnabled != layoutEnabled) {
2523            mLayoutEnabled = layoutEnabled;
2524            requestLayout();
2525        }
2526    }
2527
2528    final static class SavedState implements Parcelable {
2529
2530        int index; // index inside adapter of the current view
2531        Bundle childStates = Bundle.EMPTY;
2532
2533        @Override
2534        public void writeToParcel(Parcel out, int flags) {
2535            out.writeInt(index);
2536            out.writeBundle(childStates);
2537        }
2538
2539        @SuppressWarnings("hiding")
2540        public static final Parcelable.Creator<SavedState> CREATOR =
2541                new Parcelable.Creator<SavedState>() {
2542                    @Override
2543                    public SavedState createFromParcel(Parcel in) {
2544                        return new SavedState(in);
2545                    }
2546
2547                    @Override
2548                    public SavedState[] newArray(int size) {
2549                        return new SavedState[size];
2550                    }
2551                };
2552
2553        @Override
2554        public int describeContents() {
2555            return 0;
2556        }
2557
2558        SavedState(Parcel in) {
2559            index = in.readInt();
2560            childStates = in.readBundle(GridLayoutManager.class.getClassLoader());
2561        }
2562
2563        SavedState() {
2564        }
2565    }
2566
2567    @Override
2568    public Parcelable onSaveInstanceState() {
2569        SavedState ss = new SavedState();
2570        for (int i = 0, count = getChildCount(); i < count; i++) {
2571            View view = getChildAt(i);
2572            int position = getPositionByView(view);
2573            if (position != NO_POSITION) {
2574                mChildrenStates.saveOnScreenView(view, position);
2575            }
2576        }
2577        ss.index = getSelection();
2578        ss.childStates = mChildrenStates.getChildStates();
2579        return ss;
2580    }
2581
2582    @Override
2583    public void onRestoreInstanceState(Parcelable state) {
2584        if (!(state instanceof SavedState)) {
2585            return;
2586        }
2587        SavedState ss = (SavedState)state;
2588        mLoadingState = ss;
2589        mForceFullLayout = true;
2590        requestLayout();
2591    }
2592}
2593