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