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