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