GridLayoutManager.java revision c35968d173f900d8024bdf38174e2225c9a7f311
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                    mMeasuredDimension[0] = view.getMeasuredWidth();
831                    mMeasuredDimension[1] = view.getMeasuredHeight();
832                }
833                final int secondarySize = mOrientation == HORIZONTAL ?
834                        mMeasuredDimension[1] : mMeasuredDimension[0];
835                if (secondarySize > rowSize) {
836                    rowSize = secondarySize;
837                }
838            }
839            if (DEBUG) Log.v(getTag(), "row " + rowIndex + " rowItemCount " + rowItemCount +
840                    " rowSize " + rowSize);
841
842            if (mRowSizeSecondary[rowIndex] != rowSize) {
843                if (DEBUG) Log.v(getTag(), "row size secondary changed: " + mRowSizeSecondary[rowIndex] +
844                        ", " + rowSize);
845
846                mRowSizeSecondary[rowIndex] = rowSize;
847                changed = true;
848            }
849        }
850
851        return changed;
852    }
853
854    /**
855     * Checks if we need to update row secondary sizes.
856     */
857    private void updateRowSecondarySizeRefresh() {
858        mRowSecondarySizeRefresh = processRowSizeSecondary(false);
859        if (mRowSecondarySizeRefresh) {
860            if (DEBUG) Log.v(getTag(), "mRowSecondarySizeRefresh now set");
861            forceRequestLayout();
862        }
863    }
864
865    private void forceRequestLayout() {
866        if (DEBUG) Log.v(getTag(), "forceRequestLayout");
867        // RecyclerView prevents us from requesting layout in many cases
868        // (during layout, during scroll, etc.)
869        // For secondary row size wrap_content support we currently need a
870        // second layout pass to update the measured size after having measured
871        // and added child views in layoutChildren.
872        // Force the second layout by posting a delayed runnable.
873        // TODO: investigate allowing a second layout pass,
874        // or move child add/measure logic to the measure phase.
875        mBaseGridView.getHandler().post(new Runnable() {
876           @Override
877           public void run() {
878               if (DEBUG) Log.v(getTag(), "request Layout from runnable");
879               requestLayout();
880           }
881        });
882    }
883
884    @Override
885    public void onMeasure(Recycler recycler, State state, int widthSpec, int heightSpec) {
886        saveContext(recycler, state);
887
888        int sizePrimary, sizeSecondary, modeSecondary, paddingSecondary;
889        int measuredSizeSecondary;
890        if (mOrientation == HORIZONTAL) {
891            sizePrimary = MeasureSpec.getSize(widthSpec);
892            sizeSecondary = MeasureSpec.getSize(heightSpec);
893            modeSecondary = MeasureSpec.getMode(heightSpec);
894            paddingSecondary = getPaddingTop() + getPaddingBottom();
895        } else {
896            sizeSecondary = MeasureSpec.getSize(widthSpec);
897            sizePrimary = MeasureSpec.getSize(heightSpec);
898            modeSecondary = MeasureSpec.getMode(widthSpec);
899            paddingSecondary = getPaddingLeft() + getPaddingRight();
900        }
901        if (DEBUG) Log.v(getTag(), "onMeasure widthSpec " + Integer.toHexString(widthSpec) +
902                " heightSpec " + Integer.toHexString(heightSpec) +
903                " modeSecondary " + Integer.toHexString(modeSecondary) +
904                " sizeSecondary " + sizeSecondary + " " + this);
905
906        mMaxSizeSecondary = sizeSecondary;
907
908        if (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) {
909            mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested;
910            mFixedRowSizeSecondary = 0;
911
912            if (mRowSizeSecondary == null || mRowSizeSecondary.length != mNumRows) {
913                mRowSizeSecondary = new int[mNumRows];
914            }
915
916            // Measure all current children and update cached row heights
917            processRowSizeSecondary(true);
918
919            switch (modeSecondary) {
920            case MeasureSpec.UNSPECIFIED:
921                measuredSizeSecondary = getSizeSecondary() + paddingSecondary;
922                break;
923            case MeasureSpec.AT_MOST:
924                measuredSizeSecondary = Math.min(getSizeSecondary() + paddingSecondary,
925                        mMaxSizeSecondary);
926                break;
927            case MeasureSpec.EXACTLY:
928                measuredSizeSecondary = mMaxSizeSecondary;
929                break;
930            default:
931                throw new IllegalStateException("wrong spec");
932            }
933
934        } else {
935            switch (modeSecondary) {
936            case MeasureSpec.UNSPECIFIED:
937                if (mRowSizeSecondaryRequested == 0) {
938                    if (mOrientation == HORIZONTAL) {
939                        throw new IllegalStateException("Must specify rowHeight or view height");
940                    } else {
941                        throw new IllegalStateException("Must specify columnWidth or view width");
942                    }
943                }
944                mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
945                mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested;
946                measuredSizeSecondary = mFixedRowSizeSecondary * mNumRows + mMarginSecondary
947                    * (mNumRows - 1) + paddingSecondary;
948                break;
949            case MeasureSpec.AT_MOST:
950            case MeasureSpec.EXACTLY:
951                if (mNumRowsRequested == 0 && mRowSizeSecondaryRequested == 0) {
952                    mNumRows = 1;
953                    mFixedRowSizeSecondary = sizeSecondary - paddingSecondary;
954                } else if (mNumRowsRequested == 0) {
955                    mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
956                    mNumRows = (sizeSecondary + mMarginSecondary)
957                        / (mRowSizeSecondaryRequested + mMarginSecondary);
958                } else if (mRowSizeSecondaryRequested == 0) {
959                    mNumRows = mNumRowsRequested;
960                    mFixedRowSizeSecondary = (sizeSecondary - paddingSecondary - mMarginSecondary
961                            * (mNumRows - 1)) / mNumRows;
962                } else {
963                    mNumRows = mNumRowsRequested;
964                    mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
965                }
966                measuredSizeSecondary = sizeSecondary;
967                if (modeSecondary == MeasureSpec.AT_MOST) {
968                    int childrenSize = mFixedRowSizeSecondary * mNumRows + mMarginSecondary
969                        * (mNumRows - 1) + paddingSecondary;
970                    if (childrenSize < measuredSizeSecondary) {
971                        measuredSizeSecondary = childrenSize;
972                    }
973                }
974                break;
975            default:
976                throw new IllegalStateException("wrong spec");
977            }
978        }
979        if (mOrientation == HORIZONTAL) {
980            setMeasuredDimension(sizePrimary, measuredSizeSecondary);
981        } else {
982            setMeasuredDimension(measuredSizeSecondary, sizePrimary);
983        }
984        if (DEBUG) {
985            Log.v(getTag(), "onMeasure sizePrimary " + sizePrimary +
986                    " measuredSizeSecondary " + measuredSizeSecondary +
987                    " mFixedRowSizeSecondary " + mFixedRowSizeSecondary +
988                    " mNumRows " + mNumRows);
989        }
990
991        leaveContext();
992    }
993
994    private void measureChild(View child) {
995        final ViewGroup.LayoutParams lp = child.getLayoutParams();
996        final int secondarySpec = (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) ?
997                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) :
998                MeasureSpec.makeMeasureSpec(mFixedRowSizeSecondary, MeasureSpec.EXACTLY);
999        int widthSpec, heightSpec;
1000
1001        if (mOrientation == HORIZONTAL) {
1002            widthSpec = ViewGroup.getChildMeasureSpec(
1003                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
1004                    0, lp.width);
1005            heightSpec = ViewGroup.getChildMeasureSpec(secondarySpec, 0, lp.height);
1006        } else {
1007            heightSpec = ViewGroup.getChildMeasureSpec(
1008                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
1009                    0, lp.height);
1010            widthSpec = ViewGroup.getChildMeasureSpec(secondarySpec, 0, lp.width);
1011        }
1012
1013        child.measure(widthSpec, heightSpec);
1014
1015        if (DEBUG) Log.v(getTag(), "measureChild secondarySpec " + Integer.toHexString(secondarySpec) +
1016                " widthSpec " + Integer.toHexString(widthSpec) +
1017                " heightSpec " + Integer.toHexString(heightSpec) +
1018                " measuredWidth " + child.getMeasuredWidth() +
1019                " measuredHeight " + child.getMeasuredHeight());
1020        if (DEBUG) Log.v(getTag(), "child lp width " + lp.width + " height " + lp.height);
1021    }
1022
1023    private StaggeredGrid.Provider mGridProvider = new StaggeredGrid.Provider() {
1024
1025        @Override
1026        public int getCount() {
1027            return mState.getItemCount();
1028        }
1029
1030        @Override
1031        public void createItem(int index, int rowIndex, boolean append) {
1032            View v = getViewForPosition(index);
1033            if (mFirstVisiblePos >= 0) {
1034                // when StaggeredGrid append or prepend item, we must guarantee
1035                // that sibling item has created views already.
1036                if (append && index != mLastVisiblePos + 1) {
1037                    throw new RuntimeException();
1038                } else if (!append && index != mFirstVisiblePos - 1) {
1039                    throw new RuntimeException();
1040                }
1041            }
1042
1043            // See recyclerView docs:  we don't need re-add scraped view if it was removed.
1044            if (!((RecyclerView.LayoutParams) v.getLayoutParams()).isItemRemoved()) {
1045                if (append) {
1046                    addView(v);
1047                } else {
1048                    addView(v, 0);
1049                }
1050                measureChild(v);
1051            }
1052
1053            int length = mOrientation == HORIZONTAL ? v.getMeasuredWidth() : v.getMeasuredHeight();
1054            int start, end;
1055            if (append) {
1056                start = mRows[rowIndex].high;
1057                if (start != mRows[rowIndex].low) {
1058                    // if there are existing item in the row,  add margin between
1059                    start += mMarginPrimary;
1060                } else {
1061                    final int lastRow = mRows.length - 1;
1062                    if (lastRow != rowIndex && mRows[lastRow].high != mRows[lastRow].low) {
1063                        // if there are existing item in the last row, insert
1064                        // the new item after the last item of last row.
1065                        start = mRows[lastRow].high + mMarginPrimary;
1066                    }
1067                }
1068                end = start + length;
1069                mRows[rowIndex].high = end;
1070            } else {
1071                end = mRows[rowIndex].low;
1072                if (end != mRows[rowIndex].high) {
1073                    end -= mMarginPrimary;
1074                } else if (0 != rowIndex && mRows[0].high != mRows[0].low) {
1075                    // if there are existing item in the first row, insert
1076                    // the new item before the first item of first row.
1077                    end = mRows[0].low - mMarginPrimary;
1078                }
1079                start = end - length;
1080                mRows[rowIndex].low = start;
1081            }
1082            if (mFirstVisiblePos < 0) {
1083                mFirstVisiblePos = mLastVisiblePos = index;
1084            } else {
1085                if (append) {
1086                    mLastVisiblePos++;
1087                } else {
1088                    mFirstVisiblePos--;
1089                }
1090            }
1091            if (DEBUG) Log.v(getTag(), "start " + start + " end " + end);
1092            int startSecondary = getRowStartSecondary(rowIndex) - mScrollOffsetSecondary;
1093            layoutChild(rowIndex, v, start - mScrollOffsetPrimary, end - mScrollOffsetPrimary,
1094                    startSecondary);
1095            if (DEBUG) {
1096                Log.d(getTag(), "addView " + index + " " + v);
1097            }
1098            if (index == mFirstVisiblePos) {
1099                updateScrollMin();
1100            }
1101            if (index == mLastVisiblePos) {
1102                updateScrollMax();
1103            }
1104        }
1105    };
1106
1107    private void layoutChild(int rowIndex, View v, int start, int end, int startSecondary) {
1108        int sizeSecondary = mOrientation == HORIZONTAL ? v.getMeasuredHeight()
1109                : v.getMeasuredWidth();
1110        if (mFixedRowSizeSecondary > 0) {
1111            sizeSecondary = Math.min(sizeSecondary, mFixedRowSizeSecondary);
1112        }
1113        final int verticalGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
1114        final int horizontalGravity = mGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
1115        if (mOrientation == HORIZONTAL && verticalGravity == Gravity.TOP
1116                || mOrientation == VERTICAL && horizontalGravity == Gravity.LEFT) {
1117            // do nothing
1118        } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.BOTTOM
1119                || mOrientation == VERTICAL && horizontalGravity == Gravity.RIGHT) {
1120            startSecondary += getRowSizeSecondary(rowIndex) - sizeSecondary;
1121        } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.CENTER_VERTICAL
1122                || mOrientation == VERTICAL && horizontalGravity == Gravity.CENTER_HORIZONTAL) {
1123            startSecondary += (getRowSizeSecondary(rowIndex) - sizeSecondary) / 2;
1124        }
1125        int left, top, right, bottom;
1126        if (mOrientation == HORIZONTAL) {
1127            left = start;
1128            top = startSecondary;
1129            right = end;
1130            bottom = startSecondary + sizeSecondary;
1131        } else {
1132            top = start;
1133            left = startSecondary;
1134            bottom = end;
1135            right = startSecondary + sizeSecondary;
1136        }
1137        v.layout(left, top, right, bottom);
1138        updateChildOpticalInsets(v, left, top, right, bottom);
1139        updateChildAlignments(v);
1140    }
1141
1142    private void updateChildOpticalInsets(View v, int left, int top, int right, int bottom) {
1143        LayoutParams p = (LayoutParams) v.getLayoutParams();
1144        p.setOpticalInsets(left - v.getLeft(), top - v.getTop(),
1145                v.getRight() - right, v.getBottom() - bottom);
1146    }
1147
1148    private void updateChildAlignments(View v) {
1149        LayoutParams p = (LayoutParams) v.getLayoutParams();
1150        p.setAlignX(mItemAlignment.horizontal.getAlignmentPosition(v));
1151        p.setAlignY(mItemAlignment.vertical.getAlignmentPosition(v));
1152    }
1153
1154    private void updateChildAlignments() {
1155        for (int i = 0, c = getChildCount(); i < c; i++) {
1156            updateChildAlignments(getChildAt(i));
1157        }
1158    }
1159
1160    private boolean needsAppendVisibleItem() {
1161        if (mLastVisiblePos < mFocusPosition) {
1162            return true;
1163        }
1164        int right = mScrollOffsetPrimary + mSizePrimary;
1165        for (int i = 0; i < mNumRows; i++) {
1166            if (mRows[i].low == mRows[i].high) {
1167                if (mRows[i].high < right) {
1168                    return true;
1169                }
1170            } else if (mRows[i].high < right - mMarginPrimary) {
1171                return true;
1172            }
1173        }
1174        return false;
1175    }
1176
1177    private boolean needsPrependVisibleItem() {
1178        if (mFirstVisiblePos > mFocusPosition) {
1179            return true;
1180        }
1181        for (int i = 0; i < mNumRows; i++) {
1182            if (mRows[i].low == mRows[i].high) {
1183                if (mRows[i].low > mScrollOffsetPrimary) {
1184                    return true;
1185                }
1186            } else if (mRows[i].low - mMarginPrimary > mScrollOffsetPrimary) {
1187                return true;
1188            }
1189        }
1190        return false;
1191    }
1192
1193    // Append one column if possible and return true if reach end.
1194    private boolean appendOneVisibleItem() {
1195        while (true) {
1196            if (mLastVisiblePos != NO_POSITION && mLastVisiblePos < mState.getItemCount() -1 &&
1197                    mLastVisiblePos < mGrid.getLastIndex()) {
1198                // append invisible view of saved location till last row
1199                final int index = mLastVisiblePos + 1;
1200                final int row = mGrid.getLocation(index).row;
1201                mGridProvider.createItem(index, row, true);
1202                if (row == mNumRows - 1) {
1203                    return false;
1204                }
1205            } else if ((mLastVisiblePos == NO_POSITION && mState.getItemCount() > 0) ||
1206                    (mLastVisiblePos != NO_POSITION &&
1207                            mLastVisiblePos < mState.getItemCount() - 1)) {
1208                mGrid.appendItems(mScrollOffsetPrimary + mSizePrimary);
1209                return false;
1210            } else {
1211                return true;
1212            }
1213        }
1214    }
1215
1216    private void appendVisibleItems() {
1217        while (needsAppendVisibleItem()) {
1218            if (appendOneVisibleItem()) {
1219                break;
1220            }
1221        }
1222    }
1223
1224    // Prepend one column if possible and return true if reach end.
1225    private boolean prependOneVisibleItem() {
1226        while (true) {
1227            if (mFirstVisiblePos > 0) {
1228                if (mFirstVisiblePos > mGrid.getFirstIndex()) {
1229                    // prepend invisible view of saved location till first row
1230                    final int index = mFirstVisiblePos - 1;
1231                    final int row = mGrid.getLocation(index).row;
1232                    mGridProvider.createItem(index, row, false);
1233                    if (row == 0) {
1234                        return false;
1235                    }
1236                } else {
1237                    mGrid.prependItems(mScrollOffsetPrimary);
1238                    return false;
1239                }
1240            } else {
1241                return true;
1242            }
1243        }
1244    }
1245
1246    private void prependVisibleItems() {
1247        while (needsPrependVisibleItem()) {
1248            if (prependOneVisibleItem()) {
1249                break;
1250            }
1251        }
1252    }
1253
1254    private void removeChildAt(int position) {
1255        View v = findViewByPosition(position);
1256        if (v != null) {
1257            if (DEBUG) {
1258                Log.d(getTag(), "removeAndRecycleViewAt " + position);
1259            }
1260            removeAndRecycleView(v, mRecycler);
1261        }
1262    }
1263
1264    private void removeInvisibleViewsAtEnd() {
1265        if (!mPruneChild) {
1266            return;
1267        }
1268        boolean update = false;
1269        while(mLastVisiblePos > mFirstVisiblePos && mLastVisiblePos > mFocusPosition) {
1270            View view = findViewByPosition(mLastVisiblePos);
1271            if (getViewMin(view) > mSizePrimary) {
1272                removeChildAt(mLastVisiblePos);
1273                mLastVisiblePos--;
1274                update = true;
1275            } else {
1276                break;
1277            }
1278        }
1279        if (update) {
1280            updateRowsMinMax();
1281        }
1282    }
1283
1284    private void removeInvisibleViewsAtFront() {
1285        if (!mPruneChild) {
1286            return;
1287        }
1288        boolean update = false;
1289        while(mLastVisiblePos > mFirstVisiblePos && mFirstVisiblePos < mFocusPosition) {
1290            View view = findViewByPosition(mFirstVisiblePos);
1291            if (getViewMax(view) < 0) {
1292                removeChildAt(mFirstVisiblePos);
1293                mFirstVisiblePos++;
1294                update = true;
1295            } else {
1296                break;
1297            }
1298        }
1299        if (update) {
1300            updateRowsMinMax();
1301        }
1302    }
1303
1304    private void updateRowsMinMax() {
1305        if (mFirstVisiblePos < 0) {
1306            return;
1307        }
1308        for (int i = 0; i < mNumRows; i++) {
1309            mRows[i].low = Integer.MAX_VALUE;
1310            mRows[i].high = Integer.MIN_VALUE;
1311        }
1312        for (int i = mFirstVisiblePos; i <= mLastVisiblePos; i++) {
1313            View view = findViewByPosition(i);
1314            int row = mGrid.getLocation(i).row;
1315            int low = getViewMin(view) + mScrollOffsetPrimary;
1316            if (low < mRows[row].low) {
1317                mRows[row].low = low;
1318            }
1319            int high = getViewMax(view) + mScrollOffsetPrimary;
1320            if (high > mRows[row].high) {
1321                mRows[row].high = high;
1322            }
1323        }
1324    }
1325
1326    // Fast layout when there is no structure change, adapter change, etc.
1327    protected void fastRelayout() {
1328        initScrollController();
1329
1330        List<Integer>[] rows = mGrid.getItemPositionsInRows(mFirstVisiblePos, mLastVisiblePos);
1331
1332        // relayout and repositioning views on each row
1333        for (int i = 0; i < mNumRows; i++) {
1334            List<Integer> row = rows[i];
1335            final int startSecondary = getRowStartSecondary(i) - mScrollOffsetSecondary;
1336            for (int j = 0, size = row.size(); j < size; j++) {
1337                final int position = row.get(j);
1338                final View view = findViewByPosition(position);
1339                int primaryDelta, start, end;
1340
1341                if (mOrientation == HORIZONTAL) {
1342                    final int primarySize = view.getMeasuredWidth();
1343                    if (view.isLayoutRequested()) {
1344                        measureChild(view);
1345                    }
1346                    start = getViewMin(view);
1347                    end = start + view.getMeasuredWidth();
1348                    primaryDelta = view.getMeasuredWidth() - primarySize;
1349                    if (primaryDelta != 0) {
1350                        for (int k = j + 1; k < size; k++) {
1351                            findViewByPosition(row.get(k)).offsetLeftAndRight(primaryDelta);
1352                        }
1353                    }
1354                } else {
1355                    final int primarySize = view.getMeasuredHeight();
1356                    if (view.isLayoutRequested()) {
1357                        measureChild(view);
1358                    }
1359                    start = getViewMin(view);
1360                    end = start + view.getMeasuredHeight();
1361                    primaryDelta = view.getMeasuredHeight() - primarySize;
1362                    if (primaryDelta != 0) {
1363                        for (int k = j + 1; k < size; k++) {
1364                            findViewByPosition(row.get(k)).offsetTopAndBottom(primaryDelta);
1365                        }
1366                    }
1367                }
1368                layoutChild(i, view, start, end, startSecondary);
1369            }
1370        }
1371
1372        updateRowsMinMax();
1373        appendVisibleItems();
1374        prependVisibleItems();
1375
1376        updateRowsMinMax();
1377        updateScrollMin();
1378        updateScrollMax();
1379        updateScrollSecondAxis();
1380
1381        if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
1382            View focusView = findViewByPosition(mFocusPosition == NO_POSITION ? 0 : mFocusPosition);
1383            scrollToView(focusView, false);
1384        }
1385    }
1386
1387    @Override
1388    public boolean supportsPredictiveItemAnimations() {
1389        return mAnimateChildLayout;
1390    }
1391
1392    private void removeAndRecycleAllViews(RecyclerView.Recycler recycler) {
1393        if (DEBUG) Log.v(TAG, "removeAndRecycleAllViews " + getChildCount());
1394        for (int i = getChildCount() - 1; i >= 0; i--) {
1395            removeAndRecycleViewAt(i, recycler);
1396        }
1397    }
1398
1399    // Lays out items based on the current scroll position
1400    @Override
1401    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
1402        if (DEBUG) {
1403            Log.v(getTag(), "layoutChildren start numRows " + mNumRows + " mScrollOffsetSecondary "
1404                    + mScrollOffsetSecondary + " mScrollOffsetPrimary " + mScrollOffsetPrimary
1405                    + " inPreLayout " + state.isPreLayout()
1406                    + " didStructureChange " + state.didStructureChange()
1407                    + " mForceFullLayout " + mForceFullLayout);
1408            Log.v(getTag(), "width " + getWidth() + " height " + getHeight());
1409        }
1410
1411        if (mNumRows == 0) {
1412            // haven't done measure yet
1413            return;
1414        }
1415        final int itemCount = state.getItemCount();
1416        if (itemCount < 0) {
1417            return;
1418        }
1419
1420        if (!mLayoutEnabled) {
1421            discardLayoutInfo();
1422            removeAndRecycleAllViews(recycler);
1423            return;
1424        }
1425        mInLayout = true;
1426
1427        saveContext(recycler, state);
1428        // Track the old focus view so we can adjust our system scroll position
1429        // so that any scroll animations happening now will remain valid.
1430        // We must use same delta in Pre Layout (if prelayout exists) and second layout.
1431        // So we cache the deltas in PreLayout and use it in second layout.
1432        int delta = 0, deltaSecondary = 0;
1433        if (!state.isPreLayout() && mUseDeltaInPreLayout) {
1434            delta = mDeltaInPreLayout;
1435            deltaSecondary = mDeltaSecondaryInPreLayout;
1436        } else {
1437            if (mFocusPosition != NO_POSITION
1438                    && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
1439                View focusView = findViewByPosition(mFocusPosition);
1440                if (focusView != null) {
1441                    delta = mWindowAlignment.mainAxis().getSystemScrollPos(
1442                            getViewCenter(focusView) + mScrollOffsetPrimary) - mScrollOffsetPrimary;
1443                    deltaSecondary =
1444                        mWindowAlignment.secondAxis().getSystemScrollPos(
1445                                getViewCenterSecondary(focusView) + mScrollOffsetSecondary)
1446                        - mScrollOffsetSecondary;
1447                    if (mUseDeltaInPreLayout = state.isPreLayout()) {
1448                        mDeltaInPreLayout = delta;
1449                        mDeltaSecondaryInPreLayout = deltaSecondary;
1450                    }
1451                }
1452            }
1453        }
1454
1455        final boolean hasDoneFirstLayout = hasDoneFirstLayout();
1456        int savedFocusPos = mFocusPosition;
1457        boolean fastRelayout = false;
1458        if (!mState.didStructureChange() && !mForceFullLayout && hasDoneFirstLayout) {
1459            fastRelayout = true;
1460            fastRelayout();
1461        } else {
1462            boolean hadFocus = mBaseGridView.hasFocus();
1463
1464            int newFocusPosition = init(mFocusPosition);
1465            if (DEBUG) {
1466                Log.v(getTag(), "mFocusPosition " + mFocusPosition + " newFocusPosition "
1467                    + newFocusPosition);
1468            }
1469
1470            // depending on result of init(), either recreating everything
1471            // or try to reuse the row start positions near mFocusPosition
1472            if (mGrid.getSize() == 0) {
1473                // this is a fresh creating all items, starting from
1474                // mFocusPosition with a estimated row index.
1475                mGrid.setStart(newFocusPosition, StaggeredGrid.START_DEFAULT);
1476
1477                // Can't track the old focus view
1478                delta = deltaSecondary = 0;
1479
1480            } else {
1481                // mGrid remembers Locations for the column that
1482                // contains mFocusePosition and also mRows remembers start
1483                // positions of each row.
1484                // Manually re-create child views for that column
1485                int firstIndex = mGrid.getFirstIndex();
1486                int lastIndex = mGrid.getLastIndex();
1487                for (int i = firstIndex; i <= lastIndex; i++) {
1488                    mGridProvider.createItem(i, mGrid.getLocation(i).row, true);
1489                }
1490            }
1491            // add visible views at end until reach the end of window
1492            appendVisibleItems();
1493            // add visible views at front until reach the start of window
1494            prependVisibleItems();
1495            // multiple rounds: scrollToView of first round may drag first/last child into
1496            // "visible window" and we update scrollMin/scrollMax then run second scrollToView
1497            int oldFirstVisible;
1498            int oldLastVisible;
1499            do {
1500                oldFirstVisible = mFirstVisiblePos;
1501                oldLastVisible = mLastVisiblePos;
1502                View focusView = findViewByPosition(newFocusPosition);
1503                // we need force to initialize the child view's position
1504                scrollToView(focusView, false);
1505                if (focusView != null && hadFocus) {
1506                    focusView.requestFocus();
1507                }
1508                appendVisibleItems();
1509                prependVisibleItems();
1510                removeInvisibleViewsAtFront();
1511                removeInvisibleViewsAtEnd();
1512            } while (mFirstVisiblePos != oldFirstVisible || mLastVisiblePos != oldLastVisible);
1513        }
1514        mForceFullLayout = false;
1515
1516        if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
1517            scrollDirectionPrimary(-delta);
1518            scrollDirectionSecondary(-deltaSecondary);
1519        }
1520        appendVisibleItems();
1521        prependVisibleItems();
1522        removeInvisibleViewsAtFront();
1523        removeInvisibleViewsAtEnd();
1524
1525        if (DEBUG) {
1526            StringWriter sw = new StringWriter();
1527            PrintWriter pw = new PrintWriter(sw);
1528            mGrid.debugPrint(pw);
1529            Log.d(getTag(), sw.toString());
1530        }
1531
1532        if (mRowSecondarySizeRefresh) {
1533            mRowSecondarySizeRefresh = false;
1534        } else {
1535            updateRowSecondarySizeRefresh();
1536        }
1537
1538        if (!state.isPreLayout()) {
1539            mUseDeltaInPreLayout = false;
1540            if (!fastRelayout || mFocusPosition != savedFocusPos) {
1541                dispatchChildSelected();
1542            }
1543        }
1544        mInLayout = false;
1545        leaveContext();
1546        if (DEBUG) Log.v(getTag(), "layoutChildren end");
1547    }
1548
1549    private void offsetChildrenSecondary(int increment) {
1550        final int childCount = getChildCount();
1551        if (mOrientation == HORIZONTAL) {
1552            for (int i = 0; i < childCount; i++) {
1553                getChildAt(i).offsetTopAndBottom(increment);
1554            }
1555        } else {
1556            for (int i = 0; i < childCount; i++) {
1557                getChildAt(i).offsetLeftAndRight(increment);
1558            }
1559        }
1560    }
1561
1562    private void offsetChildrenPrimary(int increment) {
1563        final int childCount = getChildCount();
1564        if (mOrientation == VERTICAL) {
1565            for (int i = 0; i < childCount; i++) {
1566                getChildAt(i).offsetTopAndBottom(increment);
1567            }
1568        } else {
1569            for (int i = 0; i < childCount; i++) {
1570                getChildAt(i).offsetLeftAndRight(increment);
1571            }
1572        }
1573    }
1574
1575    @Override
1576    public int scrollHorizontallyBy(int dx, Recycler recycler, RecyclerView.State state) {
1577        if (DEBUG) Log.v(getTag(), "scrollHorizontallyBy " + dx);
1578        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1579            return 0;
1580        }
1581        saveContext(recycler, state);
1582        int result;
1583        if (mOrientation == HORIZONTAL) {
1584            result = scrollDirectionPrimary(dx);
1585        } else {
1586            result = scrollDirectionSecondary(dx);
1587        }
1588        leaveContext();
1589        return result;
1590    }
1591
1592    @Override
1593    public int scrollVerticallyBy(int dy, Recycler recycler, RecyclerView.State state) {
1594        if (DEBUG) Log.v(getTag(), "scrollVerticallyBy " + dy);
1595        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1596            return 0;
1597        }
1598        saveContext(recycler, state);
1599        int result;
1600        if (mOrientation == VERTICAL) {
1601            result = scrollDirectionPrimary(dy);
1602        } else {
1603            result = scrollDirectionSecondary(dy);
1604        }
1605        leaveContext();
1606        return result;
1607    }
1608
1609    // scroll in main direction may add/prune views
1610    private int scrollDirectionPrimary(int da) {
1611        if (da > 0) {
1612            if (!mWindowAlignment.mainAxis().isMaxUnknown()) {
1613                int maxScroll = mWindowAlignment.mainAxis().getMaxScroll();
1614                if (mScrollOffsetPrimary + da > maxScroll) {
1615                    da = maxScroll - mScrollOffsetPrimary;
1616                }
1617            }
1618        } else if (da < 0) {
1619            if (!mWindowAlignment.mainAxis().isMinUnknown()) {
1620                int minScroll = mWindowAlignment.mainAxis().getMinScroll();
1621                if (mScrollOffsetPrimary + da < minScroll) {
1622                    da = minScroll - mScrollOffsetPrimary;
1623                }
1624            }
1625        }
1626        if (da == 0) {
1627            return 0;
1628        }
1629        offsetChildrenPrimary(-da);
1630        mScrollOffsetPrimary += da;
1631        if (mInLayout) {
1632            return da;
1633        }
1634
1635        int childCount = getChildCount();
1636        boolean updated;
1637
1638        if (da > 0) {
1639            appendVisibleItems();
1640        } else if (da < 0) {
1641            prependVisibleItems();
1642        }
1643        updated = getChildCount() > childCount;
1644        childCount = getChildCount();
1645
1646        if (da > 0) {
1647            removeInvisibleViewsAtFront();
1648        } else if (da < 0) {
1649            removeInvisibleViewsAtEnd();
1650        }
1651        updated |= getChildCount() < childCount;
1652
1653        if (updated) {
1654            updateRowSecondarySizeRefresh();
1655        }
1656
1657        mBaseGridView.invalidate();
1658        return da;
1659    }
1660
1661    // scroll in second direction will not add/prune views
1662    private int scrollDirectionSecondary(int dy) {
1663        if (dy == 0) {
1664            return 0;
1665        }
1666        offsetChildrenSecondary(-dy);
1667        mScrollOffsetSecondary += dy;
1668        mBaseGridView.invalidate();
1669        return dy;
1670    }
1671
1672    private void updateScrollMax() {
1673        if (mLastVisiblePos < 0) {
1674            return;
1675        }
1676        final boolean lastAvailable = mLastVisiblePos == mState.getItemCount() - 1;
1677        final boolean maxUnknown = mWindowAlignment.mainAxis().isMaxUnknown();
1678        if (!lastAvailable && maxUnknown) {
1679            return;
1680        }
1681        int maxEdge = Integer.MIN_VALUE;
1682        int rowIndex = -1;
1683        for (int i = 0; i < mRows.length; i++) {
1684            if (mRows[i].high > maxEdge) {
1685                maxEdge = mRows[i].high;
1686                rowIndex = i;
1687            }
1688        }
1689        int maxScroll = Integer.MAX_VALUE;
1690        for (int i = mLastVisiblePos; i >= mFirstVisiblePos; i--) {
1691            StaggeredGrid.Location location = mGrid.getLocation(i);
1692            if (location != null && location.row == rowIndex) {
1693                int savedMaxEdge = mWindowAlignment.mainAxis().getMaxEdge();
1694                mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1695                maxScroll = mWindowAlignment
1696                        .mainAxis().getSystemScrollPos(mScrollOffsetPrimary
1697                        + getViewCenter(findViewByPosition(i)));
1698                mWindowAlignment.mainAxis().setMaxEdge(savedMaxEdge);
1699                break;
1700            }
1701        }
1702        if (lastAvailable) {
1703            mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1704            mWindowAlignment.mainAxis().setMaxScroll(maxScroll);
1705            if (DEBUG) Log.v(getTag(), "updating scroll maxEdge to " + maxEdge +
1706                    " scrollMax to " + maxScroll);
1707        } else {
1708            // the maxScroll for currently last visible item is larger,
1709            // so we must invalidate the max scroll value.
1710            if (maxScroll > mWindowAlignment.mainAxis().getMaxScroll()) {
1711                mWindowAlignment.mainAxis().invalidateScrollMax();
1712                if (DEBUG) Log.v(getTag(), "Invalidate scrollMax since it should be "
1713                        + "greater than " + maxScroll);
1714            }
1715        }
1716    }
1717
1718    private void updateScrollMin() {
1719        if (mFirstVisiblePos < 0) {
1720            return;
1721        }
1722        final boolean firstAvailable = mFirstVisiblePos == 0;
1723        final boolean minUnknown = mWindowAlignment.mainAxis().isMinUnknown();
1724        if (!firstAvailable && minUnknown) {
1725            return;
1726        }
1727        int minEdge = Integer.MAX_VALUE;
1728        int rowIndex = -1;
1729        for (int i = 0; i < mRows.length; i++) {
1730            if (mRows[i].low < minEdge) {
1731                minEdge = mRows[i].low;
1732                rowIndex = i;
1733            }
1734        }
1735        int minScroll = Integer.MIN_VALUE;
1736        for (int i = mFirstVisiblePos; i <= mLastVisiblePos; i++) {
1737            StaggeredGrid.Location location = mGrid.getLocation(i);
1738            if (location != null && location.row == rowIndex) {
1739                int savedMinEdge = mWindowAlignment.mainAxis().getMinEdge();
1740                mWindowAlignment.mainAxis().setMinEdge(minEdge);
1741                minScroll = mWindowAlignment
1742                        .mainAxis().getSystemScrollPos(mScrollOffsetPrimary
1743                        + getViewCenter(findViewByPosition(i)));
1744                mWindowAlignment.mainAxis().setMinEdge(savedMinEdge);
1745                break;
1746            }
1747        }
1748        if (firstAvailable) {
1749            mWindowAlignment.mainAxis().setMinEdge(minEdge);
1750            mWindowAlignment.mainAxis().setMinScroll(minScroll);
1751            if (DEBUG) Log.v(getTag(), "updating scroll minEdge to " + minEdge +
1752                    " scrollMin to " + minScroll);
1753        } else {
1754            // the minScroll for currently first visible item is smaller,
1755            // so we must invalidate the min scroll value.
1756            if (minScroll < mWindowAlignment.mainAxis().getMinScroll()) {
1757                mWindowAlignment.mainAxis().invalidateScrollMin();
1758                if (DEBUG) Log.v(getTag(), "Invalidate scrollMin, since it should be "
1759                        + "less than " + minScroll);
1760            }
1761        }
1762    }
1763
1764    private void updateScrollSecondAxis() {
1765        mWindowAlignment.secondAxis().setMinEdge(0);
1766        mWindowAlignment.secondAxis().setMaxEdge(getSizeSecondary());
1767    }
1768
1769    private void initScrollController() {
1770        mWindowAlignment.horizontal.setSize(getWidth());
1771        mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight());
1772        mWindowAlignment.vertical.setSize(getHeight());
1773        mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom());
1774        mSizePrimary = mWindowAlignment.mainAxis().getSize();
1775
1776        if (DEBUG) {
1777            Log.v(getTag(), "initScrollController mSizePrimary " + mSizePrimary
1778                    + " mWindowAlignment " + mWindowAlignment);
1779        }
1780    }
1781
1782    public void setSelection(RecyclerView parent, int position) {
1783        setSelection(parent, position, false);
1784    }
1785
1786    public void setSelectionSmooth(RecyclerView parent, int position) {
1787        setSelection(parent, position, true);
1788    }
1789
1790    public int getSelection() {
1791        return mFocusPosition;
1792    }
1793
1794    public void setSelection(RecyclerView parent, int position, boolean smooth) {
1795        if (mFocusPosition == position) {
1796            return;
1797        }
1798        View view = findViewByPosition(position);
1799        if (view != null) {
1800            scrollToView(view, smooth);
1801        } else {
1802            mFocusPosition = position;
1803            if (!mLayoutEnabled) {
1804                return;
1805            }
1806            if (smooth) {
1807                if (!hasDoneFirstLayout()) {
1808                    Log.w(getTag(), "setSelectionSmooth should " +
1809                            "not be called before first layout pass");
1810                    return;
1811                }
1812                LinearSmoothScroller linearSmoothScroller =
1813                        new LinearSmoothScroller(parent.getContext()) {
1814                    @Override
1815                    public PointF computeScrollVectorForPosition(int targetPosition) {
1816                        if (getChildCount() == 0) {
1817                            return null;
1818                        }
1819                        final int firstChildPos = getPosition(getChildAt(0));
1820                        final int direction = targetPosition < firstChildPos ? -1 : 1;
1821                        if (mOrientation == HORIZONTAL) {
1822                            return new PointF(direction, 0);
1823                        } else {
1824                            return new PointF(0, direction);
1825                        }
1826                    }
1827                    @Override
1828                    protected void onTargetFound(View targetView,
1829                            RecyclerView.State state, Action action) {
1830                        if (hasFocus()) {
1831                            targetView.requestFocus();
1832                        } else {
1833                            dispatchChildSelected();
1834                        }
1835                        if (getScrollPosition(targetView, mTempDeltas)) {
1836                            int dx, dy;
1837                            if (mOrientation == HORIZONTAL) {
1838                                dx = mTempDeltas[0];
1839                                dy = mTempDeltas[1];
1840                            } else {
1841                                dx = mTempDeltas[1];
1842                                dy = mTempDeltas[0];
1843                            }
1844                            final int distance = (int) Math.sqrt(dx * dx + dy * dy);
1845                            final int time = calculateTimeForDeceleration(distance);
1846                            action.update(dx, dy, time, mDecelerateInterpolator);
1847                        }
1848                    }
1849                };
1850                linearSmoothScroller.setTargetPosition(position);
1851                startSmoothScroll(linearSmoothScroller);
1852            } else {
1853                mForceFullLayout = true;
1854                parent.requestLayout();
1855            }
1856        }
1857    }
1858
1859    @Override
1860    public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
1861        boolean needsLayout = false;
1862        if (itemCount != 0) {
1863            if (mFirstVisiblePos < 0) {
1864                needsLayout = true;
1865            } else if (!(positionStart > mLastVisiblePos + 1 ||
1866                    positionStart + itemCount < mFirstVisiblePos - 1)) {
1867                needsLayout = true;
1868            }
1869        }
1870        if (needsLayout) {
1871            recyclerView.requestLayout();
1872        }
1873    }
1874
1875    @Override
1876    public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) {
1877        if (mFocusSearchDisabled) {
1878            return true;
1879        }
1880        if (!mInLayout) {
1881            scrollToView(child, true);
1882        }
1883        return true;
1884    }
1885
1886    @Override
1887    public boolean requestChildRectangleOnScreen(RecyclerView parent, View view, Rect rect,
1888            boolean immediate) {
1889        if (DEBUG) Log.v(getTag(), "requestChildRectangleOnScreen " + view + " " + rect);
1890        return false;
1891    }
1892
1893    int getScrollOffsetX() {
1894        return mOrientation == HORIZONTAL ? mScrollOffsetPrimary : mScrollOffsetSecondary;
1895    }
1896
1897    int getScrollOffsetY() {
1898        return mOrientation == HORIZONTAL ? mScrollOffsetSecondary : mScrollOffsetPrimary;
1899    }
1900
1901    public void getViewSelectedOffsets(View view, int[] offsets) {
1902        int scrollOffsetX = getScrollOffsetX();
1903        int scrollOffsetY = getScrollOffsetY();
1904        int viewCenterX = scrollOffsetX + getViewCenterX(view);
1905        int viewCenterY = scrollOffsetY + getViewCenterY(view);
1906        offsets[0] = mWindowAlignment.horizontal.getSystemScrollPos(viewCenterX) - scrollOffsetX;
1907        offsets[1] = mWindowAlignment.vertical.getSystemScrollPos(viewCenterY) - scrollOffsetY;
1908    }
1909
1910    /**
1911     * Scroll to a given child view and change mFocusPosition.
1912     */
1913    private void scrollToView(View view, boolean smooth) {
1914        int newFocusPosition = getPositionByView(view);
1915        if (newFocusPosition != mFocusPosition) {
1916            mFocusPosition = newFocusPosition;
1917            if (!mInLayout) {
1918                dispatchChildSelected();
1919            }
1920        }
1921        if (mBaseGridView.isChildrenDrawingOrderEnabledInternal()) {
1922            mBaseGridView.invalidate();
1923        }
1924        if (view == null) {
1925            return;
1926        }
1927        if (!view.hasFocus() && mBaseGridView.hasFocus()) {
1928            // transfer focus to the child if it does not have focus yet (e.g. triggered
1929            // by setSelection())
1930            view.requestFocus();
1931        }
1932        if (getScrollPosition(view, mTempDeltas)) {
1933            scrollGrid(mTempDeltas[0], mTempDeltas[1], smooth);
1934        }
1935    }
1936
1937    private boolean getScrollPosition(View view, int[] deltas) {
1938        switch (mFocusScrollStrategy) {
1939        case BaseGridView.FOCUS_SCROLL_ALIGNED:
1940        default:
1941            return getAlignedPosition(view, deltas);
1942        case BaseGridView.FOCUS_SCROLL_ITEM:
1943        case BaseGridView.FOCUS_SCROLL_PAGE:
1944            return getNoneAlignedPosition(view, deltas);
1945        }
1946    }
1947
1948    private boolean getNoneAlignedPosition(View view, int[] deltas) {
1949        int pos = getPositionByView(view);
1950        int viewMin = getViewMin(view);
1951        int viewMax = getViewMax(view);
1952        // we either align "firstView" to left/top padding edge
1953        // or align "lastView" to right/bottom padding edge
1954        View firstView = null;
1955        View lastView = null;
1956        int paddingLow = mWindowAlignment.mainAxis().getPaddingLow();
1957        int clientSize = mWindowAlignment.mainAxis().getClientSize();
1958        final int row = mGrid.getLocation(pos).row;
1959        if (viewMin < paddingLow) {
1960            // view enters low padding area:
1961            firstView = view;
1962            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
1963                // scroll one "page" left/top,
1964                // align first visible item of the "page" at the low padding edge.
1965                while (!prependOneVisibleItem()) {
1966                    List<Integer> positions =
1967                            mGrid.getItemPositionsInRows(mFirstVisiblePos, pos)[row];
1968                    firstView = findViewByPosition(positions.get(0));
1969                    if (viewMax - getViewMin(firstView) > clientSize) {
1970                        if (positions.size() > 1) {
1971                            firstView = findViewByPosition(positions.get(1));
1972                        }
1973                        break;
1974                    }
1975                }
1976            }
1977        } else if (viewMax > clientSize + paddingLow) {
1978            // view enters high padding area:
1979            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
1980                // scroll whole one page right/bottom, align view at the low padding edge.
1981                firstView = view;
1982                do {
1983                    List<Integer> positions =
1984                            mGrid.getItemPositionsInRows(pos, mLastVisiblePos)[row];
1985                    lastView = findViewByPosition(positions.get(positions.size() - 1));
1986                    if (getViewMax(lastView) - viewMin > clientSize) {
1987                        lastView = null;
1988                        break;
1989                    }
1990                } while (!appendOneVisibleItem());
1991                if (lastView != null) {
1992                    // however if we reached end,  we should align last view.
1993                    firstView = null;
1994                }
1995            } else {
1996                lastView = view;
1997            }
1998        }
1999        int scrollPrimary = 0;
2000        int scrollSecondary = 0;
2001        if (firstView != null) {
2002            scrollPrimary = getViewMin(firstView) - paddingLow;
2003        } else if (lastView != null) {
2004            scrollPrimary = getViewMax(lastView) - (paddingLow + clientSize);
2005        }
2006        View secondaryAlignedView;
2007        if (firstView != null) {
2008            secondaryAlignedView = firstView;
2009        } else if (lastView != null) {
2010            secondaryAlignedView = lastView;
2011        } else {
2012            secondaryAlignedView = view;
2013        }
2014        int viewCenterSecondary = mScrollOffsetSecondary +
2015                getViewCenterSecondary(secondaryAlignedView);
2016        scrollSecondary = mWindowAlignment.secondAxis().getSystemScrollPos(viewCenterSecondary);
2017        scrollSecondary -= mScrollOffsetSecondary;
2018        if (scrollPrimary != 0 || scrollSecondary != 0) {
2019            deltas[0] = scrollPrimary;
2020            deltas[1] = scrollSecondary;
2021            return true;
2022        }
2023        return false;
2024    }
2025
2026    private boolean getAlignedPosition(View view, int[] deltas) {
2027        int viewCenterPrimary = mScrollOffsetPrimary + getViewCenter(view);
2028        int viewCenterSecondary = mScrollOffsetSecondary + getViewCenterSecondary(view);
2029
2030        int scrollPrimary = mWindowAlignment.mainAxis().getSystemScrollPos(viewCenterPrimary);
2031        int scrollSecondary = mWindowAlignment.secondAxis().getSystemScrollPos(viewCenterSecondary);
2032        if (DEBUG) {
2033            Log.v(getTag(), "getAlignedPosition " + scrollPrimary + " " + scrollSecondary
2034                    +" " + mWindowAlignment);
2035        }
2036        scrollPrimary -= mScrollOffsetPrimary;
2037        scrollSecondary -= mScrollOffsetSecondary;
2038        if (scrollPrimary != 0 || scrollSecondary != 0) {
2039            deltas[0] = scrollPrimary;
2040            deltas[1] = scrollSecondary;
2041            return true;
2042        }
2043        return false;
2044    }
2045
2046    private void scrollGrid(int scrollPrimary, int scrollSecondary, boolean smooth) {
2047        if (mInLayout) {
2048            scrollDirectionPrimary(scrollPrimary);
2049            scrollDirectionSecondary(scrollSecondary);
2050        } else {
2051            int scrollX;
2052            int scrollY;
2053            if (mOrientation == HORIZONTAL) {
2054                scrollX = scrollPrimary;
2055                scrollY = scrollSecondary;
2056            } else {
2057                scrollX = scrollSecondary;
2058                scrollY = scrollPrimary;
2059            }
2060            if (smooth) {
2061                mBaseGridView.smoothScrollBy(scrollX, scrollY);
2062            } else {
2063                mBaseGridView.scrollBy(scrollX, scrollY);
2064            }
2065        }
2066    }
2067
2068    public void setAnimateChildLayout(boolean animateChildLayout) {
2069        mAnimateChildLayout = animateChildLayout;
2070    }
2071
2072    public boolean isChildLayoutAnimated() {
2073        return mAnimateChildLayout;
2074    }
2075
2076    public void setPruneChild(boolean pruneChild) {
2077        if (mPruneChild != pruneChild) {
2078            mPruneChild = pruneChild;
2079            if (mPruneChild) {
2080                requestLayout();
2081            }
2082        }
2083    }
2084
2085    public boolean getPruneChild() {
2086        return mPruneChild;
2087    }
2088
2089    private int findImmediateChildIndex(View view) {
2090        while (view != null && view != mBaseGridView) {
2091            int index = mBaseGridView.indexOfChild(view);
2092            if (index >= 0) {
2093                return index;
2094            }
2095            view = (View) view.getParent();
2096        }
2097        return NO_POSITION;
2098    }
2099
2100    void setFocusSearchDisabled(boolean disabled) {
2101        mFocusSearchDisabled = disabled;
2102    }
2103
2104    boolean isFocusSearchDisabled() {
2105        return mFocusSearchDisabled;
2106    }
2107
2108    @Override
2109    public View onInterceptFocusSearch(View focused, int direction) {
2110        if (mFocusSearchDisabled) {
2111            return focused;
2112        }
2113        return null;
2114    }
2115
2116    boolean hasPreviousViewInSameRow(int pos) {
2117        if (mGrid == null || pos == NO_POSITION) {
2118            return false;
2119        }
2120        if (mFirstVisiblePos > 0) {
2121            return true;
2122        }
2123        final int focusedRow = mGrid.getLocation(pos).row;
2124        for (int i = getChildCount() - 1; i >= 0; i--) {
2125            int position = getPositionByIndex(i);
2126            StaggeredGrid.Location loc = mGrid.getLocation(position);
2127            if (loc != null && loc.row == focusedRow) {
2128                if (position < pos) {
2129                    return true;
2130                }
2131            }
2132        }
2133        return false;
2134    }
2135
2136    @Override
2137    public boolean onAddFocusables(RecyclerView recyclerView,
2138            ArrayList<View> views, int direction, int focusableMode) {
2139        if (mFocusSearchDisabled) {
2140            return true;
2141        }
2142        // If this viewgroup or one of its children currently has focus then we
2143        // consider our children for focus searching in main direction on the same row.
2144        // If this viewgroup has no focus and using focus align, we want the system
2145        // to ignore our children and pass focus to the viewgroup, which will pass
2146        // focus on to its children appropriately.
2147        // If this viewgroup has no focus and not using focus align, we want to
2148        // consider the child that does not overlap with padding area.
2149        if (recyclerView.hasFocus()) {
2150            final int movement = getMovement(direction);
2151            if (movement != PREV_ITEM && movement != NEXT_ITEM) {
2152                // Move on secondary direction uses default addFocusables().
2153                return false;
2154            }
2155            final View focused = recyclerView.findFocus();
2156            final int focusedPos = getPositionByIndex(findImmediateChildIndex(focused));
2157            // Add focusables of focused item.
2158            if (focusedPos != NO_POSITION) {
2159                findViewByPosition(focusedPos).addFocusables(views,  direction, focusableMode);
2160            }
2161            final int focusedRow = mGrid != null && focusedPos != NO_POSITION ?
2162                    mGrid.getLocation(focusedPos).row : NO_POSITION;
2163            // Add focusables of next neighbor of same row on the focus search direction.
2164            if (mGrid != null) {
2165                final int focusableCount = views.size();
2166                for (int i = 0, count = getChildCount(); i < count; i++) {
2167                    int index = movement == NEXT_ITEM ? i : count - 1 - i;
2168                    final View child = getChildAt(index);
2169                    if (child.getVisibility() != View.VISIBLE) {
2170                        continue;
2171                    }
2172                    int position = getPositionByIndex(index);
2173                    StaggeredGrid.Location loc = mGrid.getLocation(position);
2174                    if (focusedRow == NO_POSITION || (loc != null && loc.row == focusedRow)) {
2175                        if (focusedPos == NO_POSITION ||
2176                                (movement == NEXT_ITEM && position > focusedPos)
2177                                || (movement == PREV_ITEM && position < focusedPos)) {
2178                            child.addFocusables(views,  direction, focusableMode);
2179                            if (views.size() > focusableCount) {
2180                                break;
2181                            }
2182                        }
2183                    }
2184                }
2185            }
2186        } else {
2187            if (mFocusScrollStrategy != BaseGridView.FOCUS_SCROLL_ALIGNED) {
2188                // adding views not overlapping padding area to avoid scrolling in gaining focus
2189                int left = mWindowAlignment.mainAxis().getPaddingLow();
2190                int right = mWindowAlignment.mainAxis().getClientSize() + left;
2191                int focusableCount = views.size();
2192                for (int i = 0, count = getChildCount(); i < count; i++) {
2193                    View child = getChildAt(i);
2194                    if (child.getVisibility() == View.VISIBLE) {
2195                        if (getViewMin(child) >= left && getViewMax(child) <= right) {
2196                            child.addFocusables(views, direction, focusableMode);
2197                        }
2198                    }
2199                }
2200                // if we cannot find any, then just add all children.
2201                if (views.size() == focusableCount) {
2202                    for (int i = 0, count = getChildCount(); i < count; i++) {
2203                        View child = getChildAt(i);
2204                        if (child.getVisibility() == View.VISIBLE) {
2205                            child.addFocusables(views, direction, focusableMode);
2206                        }
2207                    }
2208                    if (views.size() != focusableCount) {
2209                        return true;
2210                    }
2211                } else {
2212                    return true;
2213                }
2214                // if still cannot find any, fall through and add itself
2215            }
2216            if (recyclerView.isFocusable()) {
2217                views.add(recyclerView);
2218            }
2219        }
2220        return true;
2221    }
2222
2223    @Override
2224    public View onFocusSearchFailed(View focused, int direction, Recycler recycler,
2225            RecyclerView.State state) {
2226        if (DEBUG) Log.v(getTag(), "onFocusSearchFailed direction " + direction);
2227
2228        saveContext(recycler, state);
2229        View view = null;
2230        int movement = getMovement(direction);
2231        final FocusFinder ff = FocusFinder.getInstance();
2232        if (movement == NEXT_ITEM) {
2233            while (view == null && !appendOneVisibleItem()) {
2234                view = ff.findNextFocus(mBaseGridView, focused, direction);
2235            }
2236        } else if (movement == PREV_ITEM){
2237            while (view == null && !prependOneVisibleItem()) {
2238                view = ff.findNextFocus(mBaseGridView, focused, direction);
2239            }
2240        }
2241        if (view == null) {
2242            // returning the same view to prevent focus lost when scrolling past the end of the list
2243            if (movement == PREV_ITEM) {
2244                view = mFocusOutFront ? null : focused;
2245            } else if (movement == NEXT_ITEM){
2246                view = mFocusOutEnd ? null : focused;
2247            }
2248        }
2249        leaveContext();
2250        if (DEBUG) Log.v(getTag(), "returning view " + view);
2251        return view;
2252    }
2253
2254    boolean gridOnRequestFocusInDescendants(RecyclerView recyclerView, int direction,
2255            Rect previouslyFocusedRect) {
2256        switch (mFocusScrollStrategy) {
2257        case BaseGridView.FOCUS_SCROLL_ALIGNED:
2258        default:
2259            return gridOnRequestFocusInDescendantsAligned(recyclerView,
2260                    direction, previouslyFocusedRect);
2261        case BaseGridView.FOCUS_SCROLL_PAGE:
2262        case BaseGridView.FOCUS_SCROLL_ITEM:
2263            return gridOnRequestFocusInDescendantsUnaligned(recyclerView,
2264                    direction, previouslyFocusedRect);
2265        }
2266    }
2267
2268    private boolean gridOnRequestFocusInDescendantsAligned(RecyclerView recyclerView,
2269            int direction, Rect previouslyFocusedRect) {
2270        View view = findViewByPosition(mFocusPosition);
2271        if (view != null) {
2272            boolean result = view.requestFocus(direction, previouslyFocusedRect);
2273            if (!result && DEBUG) {
2274                Log.w(getTag(), "failed to request focus on " + view);
2275            }
2276            return result;
2277        }
2278        return false;
2279    }
2280
2281    private boolean gridOnRequestFocusInDescendantsUnaligned(RecyclerView recyclerView,
2282            int direction, Rect previouslyFocusedRect) {
2283        // focus to view not overlapping padding area to avoid scrolling in gaining focus
2284        int index;
2285        int increment;
2286        int end;
2287        int count = getChildCount();
2288        if ((direction & View.FOCUS_FORWARD) != 0) {
2289            index = 0;
2290            increment = 1;
2291            end = count;
2292        } else {
2293            index = count - 1;
2294            increment = -1;
2295            end = -1;
2296        }
2297        int left = mWindowAlignment.mainAxis().getPaddingLow();
2298        int right = mWindowAlignment.mainAxis().getClientSize() + left;
2299        for (int i = index; i != end; i += increment) {
2300            View child = getChildAt(i);
2301            if (child.getVisibility() == View.VISIBLE) {
2302                if (getViewMin(child) >= left && getViewMax(child) <= right) {
2303                    if (child.requestFocus(direction, previouslyFocusedRect)) {
2304                        return true;
2305                    }
2306                }
2307            }
2308        }
2309        return false;
2310    }
2311
2312    private final static int PREV_ITEM = 0;
2313    private final static int NEXT_ITEM = 1;
2314    private final static int PREV_ROW = 2;
2315    private final static int NEXT_ROW = 3;
2316
2317    private int getMovement(int direction) {
2318        int movement = View.FOCUS_LEFT;
2319
2320        if (mOrientation == HORIZONTAL) {
2321            switch(direction) {
2322                case View.FOCUS_LEFT:
2323                    movement = PREV_ITEM;
2324                    break;
2325                case View.FOCUS_RIGHT:
2326                    movement = NEXT_ITEM;
2327                    break;
2328                case View.FOCUS_UP:
2329                    movement = PREV_ROW;
2330                    break;
2331                case View.FOCUS_DOWN:
2332                    movement = NEXT_ROW;
2333                    break;
2334            }
2335         } else if (mOrientation == VERTICAL) {
2336             switch(direction) {
2337                 case View.FOCUS_LEFT:
2338                     movement = PREV_ROW;
2339                     break;
2340                 case View.FOCUS_RIGHT:
2341                     movement = NEXT_ROW;
2342                     break;
2343                 case View.FOCUS_UP:
2344                     movement = PREV_ITEM;
2345                     break;
2346                 case View.FOCUS_DOWN:
2347                     movement = NEXT_ITEM;
2348                     break;
2349             }
2350         }
2351
2352        return movement;
2353    }
2354
2355    int getChildDrawingOrder(RecyclerView recyclerView, int childCount, int i) {
2356        View view = findViewByPosition(mFocusPosition);
2357        if (view == null) {
2358            return i;
2359        }
2360        int focusIndex = recyclerView.indexOfChild(view);
2361        // supposely 0 1 2 3 4 5 6 7 8 9, 4 is the center item
2362        // drawing order is 0 1 2 3 9 8 7 6 5 4
2363        if (i < focusIndex) {
2364            return i;
2365        } else if (i < childCount - 1) {
2366            return focusIndex + childCount - 1 - i;
2367        } else {
2368            return focusIndex;
2369        }
2370    }
2371
2372    @Override
2373    public void onAdapterChanged(RecyclerView.Adapter oldAdapter,
2374            RecyclerView.Adapter newAdapter) {
2375        discardLayoutInfo();
2376        mFocusPosition = NO_POSITION;
2377        super.onAdapterChanged(oldAdapter, newAdapter);
2378    }
2379
2380    private void discardLayoutInfo() {
2381        mGrid = null;
2382        mRows = null;
2383        mRowSizeSecondary = null;
2384        mFirstVisiblePos = -1;
2385        mLastVisiblePos = -1;
2386        mRowSecondarySizeRefresh = false;
2387    }
2388
2389    public void setLayoutEnabled(boolean layoutEnabled) {
2390        if (mLayoutEnabled != layoutEnabled) {
2391            mLayoutEnabled = layoutEnabled;
2392            requestLayout();
2393        }
2394    }
2395}
2396