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