GridLayoutManager.java revision 43329fc348a0134d4a3273796a6a9cf71dad04a5
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        if (!mState.didStructureChange() && !mForceFullLayout && hasDoneFirstLayout) {
1446            fastRelayout();
1447        } else {
1448            boolean hadFocus = mBaseGridView.hasFocus();
1449
1450            int newFocusPosition = init(mFocusPosition);
1451            if (DEBUG) {
1452                Log.v(getTag(), "mFocusPosition " + mFocusPosition + " newFocusPosition "
1453                    + newFocusPosition);
1454            }
1455
1456            // depending on result of init(), either recreating everything
1457            // or try to reuse the row start positions near mFocusPosition
1458            if (mGrid.getSize() == 0) {
1459                // this is a fresh creating all items, starting from
1460                // mFocusPosition with a estimated row index.
1461                mGrid.setStart(newFocusPosition, StaggeredGrid.START_DEFAULT);
1462
1463                // Can't track the old focus view
1464                delta = deltaSecondary = 0;
1465
1466            } else {
1467                // mGrid remembers Locations for the column that
1468                // contains mFocusePosition and also mRows remembers start
1469                // positions of each row.
1470                // Manually re-create child views for that column
1471                int firstIndex = mGrid.getFirstIndex();
1472                int lastIndex = mGrid.getLastIndex();
1473                for (int i = firstIndex; i <= lastIndex; i++) {
1474                    mGridProvider.createItem(i, mGrid.getLocation(i).row, true);
1475                }
1476            }
1477            // add visible views at end until reach the end of window
1478            appendVisibleItems();
1479            // add visible views at front until reach the start of window
1480            prependVisibleItems();
1481            // multiple rounds: scrollToView of first round may drag first/last child into
1482            // "visible window" and we update scrollMin/scrollMax then run second scrollToView
1483            int oldFirstVisible;
1484            int oldLastVisible;
1485            do {
1486                oldFirstVisible = mFirstVisiblePos;
1487                oldLastVisible = mLastVisiblePos;
1488                View focusView = findViewByPosition(newFocusPosition);
1489                // we need force to initialize the child view's position
1490                scrollToView(focusView, false);
1491                if (focusView != null && hadFocus) {
1492                    focusView.requestFocus();
1493                }
1494                appendVisibleItems();
1495                prependVisibleItems();
1496                removeInvisibleViewsAtFront();
1497                removeInvisibleViewsAtEnd();
1498            } while (mFirstVisiblePos != oldFirstVisible || mLastVisiblePos != oldLastVisible);
1499        }
1500        mForceFullLayout = false;
1501
1502        if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
1503            scrollDirectionPrimary(-delta);
1504            scrollDirectionSecondary(-deltaSecondary);
1505        }
1506        appendVisibleItems();
1507        prependVisibleItems();
1508        removeInvisibleViewsAtFront();
1509        removeInvisibleViewsAtEnd();
1510
1511        if (DEBUG) {
1512            StringWriter sw = new StringWriter();
1513            PrintWriter pw = new PrintWriter(sw);
1514            mGrid.debugPrint(pw);
1515            Log.d(getTag(), sw.toString());
1516        }
1517
1518        if (mRowSecondarySizeRefresh) {
1519            mRowSecondarySizeRefresh = false;
1520        } else {
1521            updateRowSecondarySizeRefresh();
1522        }
1523
1524        if (!state.isPreLayout()) {
1525            mUseDeltaInPreLayout = false;
1526            if (!hasDoneFirstLayout) {
1527                dispatchChildSelected();
1528            }
1529        }
1530        mInLayout = false;
1531        leaveContext();
1532        if (DEBUG) Log.v(getTag(), "layoutChildren end");
1533    }
1534
1535    private void offsetChildrenSecondary(int increment) {
1536        final int childCount = getChildCount();
1537        if (mOrientation == HORIZONTAL) {
1538            for (int i = 0; i < childCount; i++) {
1539                getChildAt(i).offsetTopAndBottom(increment);
1540            }
1541        } else {
1542            for (int i = 0; i < childCount; i++) {
1543                getChildAt(i).offsetLeftAndRight(increment);
1544            }
1545        }
1546        mScrollOffsetSecondary -= increment;
1547    }
1548
1549    private void offsetChildrenPrimary(int increment) {
1550        final int childCount = getChildCount();
1551        if (mOrientation == VERTICAL) {
1552            for (int i = 0; i < childCount; i++) {
1553                getChildAt(i).offsetTopAndBottom(increment);
1554            }
1555        } else {
1556            for (int i = 0; i < childCount; i++) {
1557                getChildAt(i).offsetLeftAndRight(increment);
1558            }
1559        }
1560        mScrollOffsetPrimary -= increment;
1561    }
1562
1563    @Override
1564    public int scrollHorizontallyBy(int dx, Recycler recycler, RecyclerView.State state) {
1565        if (DEBUG) Log.v(getTag(), "scrollHorizontallyBy " + dx);
1566        if (!mLayoutEnabled) {
1567            return 0;
1568        }
1569        saveContext(recycler, state);
1570        int result;
1571        if (mOrientation == HORIZONTAL) {
1572            result = scrollDirectionPrimary(dx);
1573        } else {
1574            result = scrollDirectionSecondary(dx);
1575        }
1576        leaveContext();
1577        return result;
1578    }
1579
1580    @Override
1581    public int scrollVerticallyBy(int dy, Recycler recycler, RecyclerView.State state) {
1582        if (DEBUG) Log.v(getTag(), "scrollVerticallyBy " + dy);
1583        if (!mLayoutEnabled) {
1584            return 0;
1585        }
1586        saveContext(recycler, state);
1587        int result;
1588        if (mOrientation == VERTICAL) {
1589            result = scrollDirectionPrimary(dy);
1590        } else {
1591            result = scrollDirectionSecondary(dy);
1592        }
1593        leaveContext();
1594        return result;
1595    }
1596
1597    // scroll in main direction may add/prune views
1598    private int scrollDirectionPrimary(int da) {
1599        if (da == 0) {
1600            return 0;
1601        }
1602        offsetChildrenPrimary(-da);
1603        if (mInLayout) {
1604            return da;
1605        }
1606
1607        int childCount = getChildCount();
1608        boolean updated;
1609
1610        if (da > 0) {
1611            appendVisibleItems();
1612        } else if (da < 0) {
1613            prependVisibleItems();
1614        }
1615        updated = getChildCount() > childCount;
1616        childCount = getChildCount();
1617
1618        if (da > 0) {
1619            removeInvisibleViewsAtFront();
1620        } else if (da < 0) {
1621            removeInvisibleViewsAtEnd();
1622        }
1623        updated |= getChildCount() < childCount;
1624
1625        if (updated) {
1626            updateRowSecondarySizeRefresh();
1627        }
1628
1629        mBaseGridView.invalidate();
1630        return da;
1631    }
1632
1633    // scroll in second direction will not add/prune views
1634    private int scrollDirectionSecondary(int dy) {
1635        if (dy == 0) {
1636            return 0;
1637        }
1638        offsetChildrenSecondary(-dy);
1639        mBaseGridView.invalidate();
1640        return dy;
1641    }
1642
1643    private void updateScrollMax() {
1644        if (mLastVisiblePos >= 0 && mLastVisiblePos == mState.getItemCount() - 1) {
1645            int maxEdge = Integer.MIN_VALUE;
1646            for (int i = 0; i < mRows.length; i++) {
1647                if (mRows[i].high > maxEdge) {
1648                    maxEdge = mRows[i].high;
1649                }
1650            }
1651            mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1652            if (DEBUG) Log.v(getTag(), "updating scroll maxEdge to " + maxEdge);
1653        }
1654    }
1655
1656    private void updateScrollMin() {
1657        if (mFirstVisiblePos == 0) {
1658            int minEdge = Integer.MAX_VALUE;
1659            for (int i = 0; i < mRows.length; i++) {
1660                if (mRows[i].low < minEdge) {
1661                    minEdge = mRows[i].low;
1662                }
1663            }
1664            mWindowAlignment.mainAxis().setMinEdge(minEdge);
1665            if (DEBUG) Log.v(getTag(), "updating scroll minEdge to " + minEdge);
1666        }
1667    }
1668
1669    private void updateScrollSecondAxis() {
1670        mWindowAlignment.secondAxis().setMinEdge(0);
1671        mWindowAlignment.secondAxis().setMaxEdge(getSizeSecondary());
1672    }
1673
1674    private void initScrollController() {
1675        mWindowAlignment.horizontal.setSize(getWidth());
1676        mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight());
1677        mWindowAlignment.vertical.setSize(getHeight());
1678        mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom());
1679        mSizePrimary = mWindowAlignment.mainAxis().getSize();
1680        mWindowAlignment.mainAxis().invalidateScrollMin();
1681        mWindowAlignment.mainAxis().invalidateScrollMax();
1682
1683        if (DEBUG) {
1684            Log.v(getTag(), "initScrollController mSizePrimary " + mSizePrimary
1685                    + " mWindowAlignment " + mWindowAlignment);
1686        }
1687    }
1688
1689    public void setSelection(RecyclerView parent, int position) {
1690        setSelection(parent, position, false);
1691    }
1692
1693    public void setSelectionSmooth(RecyclerView parent, int position) {
1694        setSelection(parent, position, true);
1695    }
1696
1697    public int getSelection() {
1698        return mFocusPosition;
1699    }
1700
1701    public void setSelection(RecyclerView parent, int position, boolean smooth) {
1702        if (mFocusPosition == position) {
1703            return;
1704        }
1705        View view = findViewByPosition(position);
1706        if (view != null) {
1707            scrollToView(view, smooth);
1708        } else {
1709            mFocusPosition = position;
1710            if (!mLayoutEnabled) {
1711                return;
1712            }
1713            if (smooth) {
1714                if (!hasDoneFirstLayout()) {
1715                    Log.w(getTag(), "setSelectionSmooth should " +
1716                            "not be called before first layout pass");
1717                    return;
1718                }
1719                LinearSmoothScroller linearSmoothScroller =
1720                        new LinearSmoothScroller(parent.getContext()) {
1721                    @Override
1722                    public PointF computeScrollVectorForPosition(int targetPosition) {
1723                        if (getChildCount() == 0) {
1724                            return null;
1725                        }
1726                        final int firstChildPos = getPosition(getChildAt(0));
1727                        final int direction = targetPosition < firstChildPos ? -1 : 1;
1728                        if (mOrientation == HORIZONTAL) {
1729                            return new PointF(direction, 0);
1730                        } else {
1731                            return new PointF(0, direction);
1732                        }
1733                    }
1734                    @Override
1735                    protected void onTargetFound(View targetView,
1736                            RecyclerView.State state, Action action) {
1737                        if (hasFocus()) {
1738                            targetView.requestFocus();
1739                        }
1740                        if (updateScrollPosition(targetView, false, mTempDeltas)) {
1741                            int dx, dy;
1742                            if (mOrientation == HORIZONTAL) {
1743                                dx = mTempDeltas[0];
1744                                dy = mTempDeltas[1];
1745                            } else {
1746                                dx = mTempDeltas[1];
1747                                dy = mTempDeltas[0];
1748                            }
1749                            final int distance = (int) Math.sqrt(dx * dx + dy * dy);
1750                            final int time = calculateTimeForDeceleration(distance);
1751                            action.update(dx, dy, time, mDecelerateInterpolator);
1752                        }
1753                    }
1754                };
1755                linearSmoothScroller.setTargetPosition(position);
1756                startSmoothScroll(linearSmoothScroller);
1757            } else {
1758                mForceFullLayout = true;
1759                parent.requestLayout();
1760            }
1761        }
1762    }
1763
1764    @Override
1765    public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
1766        boolean needsLayout = false;
1767        if (itemCount != 0) {
1768            if (mFirstVisiblePos < 0) {
1769                needsLayout = true;
1770            } else if (!(positionStart > mLastVisiblePos + 1 ||
1771                    positionStart + itemCount < mFirstVisiblePos - 1)) {
1772                needsLayout = true;
1773            }
1774        }
1775        if (needsLayout) {
1776            recyclerView.requestLayout();
1777        }
1778    }
1779
1780    @Override
1781    public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) {
1782        if (mFocusSearchDisabled) {
1783            return true;
1784        }
1785        if (!mInLayout) {
1786            scrollToView(child, true);
1787        }
1788        return true;
1789    }
1790
1791    @Override
1792    public boolean requestChildRectangleOnScreen(RecyclerView parent, View view, Rect rect,
1793            boolean immediate) {
1794        if (DEBUG) Log.v(getTag(), "requestChildRectangleOnScreen " + view + " " + rect);
1795        return false;
1796    }
1797
1798    int getScrollOffsetX() {
1799        return mOrientation == HORIZONTAL ? mScrollOffsetPrimary : mScrollOffsetSecondary;
1800    }
1801
1802    int getScrollOffsetY() {
1803        return mOrientation == HORIZONTAL ? mScrollOffsetSecondary : mScrollOffsetPrimary;
1804    }
1805
1806    public void getViewSelectedOffsets(View view, int[] offsets) {
1807        int scrollOffsetX = getScrollOffsetX();
1808        int scrollOffsetY = getScrollOffsetY();
1809        int viewCenterX = scrollOffsetX + getViewCenterX(view);
1810        int viewCenterY = scrollOffsetY + getViewCenterY(view);
1811        offsets[0] = mWindowAlignment.horizontal.getSystemScrollPos(viewCenterX) - scrollOffsetX;
1812        offsets[1] = mWindowAlignment.vertical.getSystemScrollPos(viewCenterY) - scrollOffsetY;
1813    }
1814
1815    /**
1816     * Scroll to a given child view and change mFocusPosition.
1817     */
1818    private void scrollToView(View view, boolean smooth) {
1819        int newFocusPosition = getPositionByView(view);
1820        if (mInLayout || newFocusPosition != mFocusPosition) {
1821            mFocusPosition = newFocusPosition;
1822            dispatchChildSelected();
1823        }
1824        if (mBaseGridView.isChildrenDrawingOrderEnabledInternal()) {
1825            mBaseGridView.invalidate();
1826        }
1827        if (view == null) {
1828            return;
1829        }
1830        if (!view.hasFocus() && mBaseGridView.hasFocus()) {
1831            // transfer focus to the child if it does not have focus yet (e.g. triggered
1832            // by setSelection())
1833            view.requestFocus();
1834        }
1835        if (updateScrollPosition(view, mInLayout, mTempDeltas)) {
1836            scrollGrid(mTempDeltas[0], mTempDeltas[1], smooth);
1837        }
1838    }
1839
1840    private boolean updateScrollPosition(View view, boolean force, int[] deltas) {
1841        switch (mFocusScrollStrategy) {
1842        case BaseGridView.FOCUS_SCROLL_ALIGNED:
1843        default:
1844            return updateAlignedPosition(view, force, deltas);
1845        case BaseGridView.FOCUS_SCROLL_ITEM:
1846        case BaseGridView.FOCUS_SCROLL_PAGE:
1847            return updateNoneAlignedPosition(view, deltas);
1848        }
1849    }
1850
1851    private boolean updateNoneAlignedPosition(View view, int[] deltas) {
1852        int pos = getPositionByView(view);
1853        int viewMin = getViewMin(view);
1854        int viewMax = getViewMax(view);
1855        // we either align "firstView" to left/top padding edge
1856        // or align "lastView" to right/bottom padding edge
1857        View firstView = null;
1858        View lastView = null;
1859        int paddingLow = mWindowAlignment.mainAxis().getPaddingLow();
1860        int clientSize = mWindowAlignment.mainAxis().getClientSize();
1861        final int row = mGrid.getLocation(pos).row;
1862        if (viewMin < paddingLow) {
1863            // view enters low padding area:
1864            firstView = view;
1865            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
1866                // scroll one "page" left/top,
1867                // align first visible item of the "page" at the low padding edge.
1868                while (!prependOneVisibleItem()) {
1869                    List<Integer> positions =
1870                            mGrid.getItemPositionsInRows(mFirstVisiblePos, pos)[row];
1871                    firstView = findViewByPosition(positions.get(0));
1872                    if (viewMax - getViewMin(firstView) > clientSize) {
1873                        if (positions.size() > 1) {
1874                            firstView = findViewByPosition(positions.get(1));
1875                        }
1876                        break;
1877                    }
1878                }
1879            }
1880        } else if (viewMax > clientSize + paddingLow) {
1881            // view enters high padding area:
1882            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
1883                // scroll whole one page right/bottom, align view at the low padding edge.
1884                firstView = view;
1885                do {
1886                    List<Integer> positions =
1887                            mGrid.getItemPositionsInRows(pos, mLastVisiblePos)[row];
1888                    lastView = findViewByPosition(positions.get(positions.size() - 1));
1889                    if (getViewMax(lastView) - viewMin > clientSize) {
1890                        lastView = null;
1891                        break;
1892                    }
1893                } while (!appendOneVisibleItem());
1894                if (lastView != null) {
1895                    // however if we reached end,  we should align last view.
1896                    firstView = null;
1897                }
1898            } else {
1899                lastView = view;
1900            }
1901        }
1902        int scrollPrimary = 0;
1903        int scrollSecondary = 0;
1904        if (firstView != null) {
1905            scrollPrimary = getViewMin(firstView) - paddingLow;
1906        } else if (lastView != null) {
1907            scrollPrimary = getViewMax(lastView) - (paddingLow + clientSize);
1908        }
1909        View secondaryAlignedView;
1910        if (firstView != null) {
1911            secondaryAlignedView = firstView;
1912        } else if (lastView != null) {
1913            secondaryAlignedView = lastView;
1914        } else {
1915            secondaryAlignedView = view;
1916        }
1917        int viewCenterSecondary = mScrollOffsetSecondary +
1918                getViewCenterSecondary(secondaryAlignedView);
1919        mWindowAlignment.secondAxis().updateScrollCenter(viewCenterSecondary);
1920        scrollSecondary = mWindowAlignment.secondAxis().getSystemScrollPos();
1921        scrollSecondary -= mScrollOffsetSecondary;
1922        if (scrollPrimary != 0 || scrollSecondary != 0) {
1923            deltas[0] = scrollPrimary;
1924            deltas[1] = scrollSecondary;
1925            return true;
1926        }
1927        return false;
1928    }
1929
1930    private boolean updateAlignedPosition(View view, boolean force, int[] deltas) {
1931        int viewCenterPrimary = mScrollOffsetPrimary + getViewCenter(view);
1932        int viewCenterSecondary = mScrollOffsetSecondary + getViewCenterSecondary(view);
1933
1934        if (force || viewCenterPrimary != mWindowAlignment.mainAxis().getScrollCenter()
1935                || viewCenterSecondary != mWindowAlignment.secondAxis().getScrollCenter()) {
1936            mWindowAlignment.mainAxis().updateScrollCenter(viewCenterPrimary);
1937            mWindowAlignment.secondAxis().updateScrollCenter(viewCenterSecondary);
1938            int scrollPrimary = mWindowAlignment.mainAxis().getSystemScrollPos();
1939            int scrollSecondary = mWindowAlignment.secondAxis().getSystemScrollPos();
1940            if (DEBUG) {
1941                Log.v(getTag(), "updateAlignedPosition " + scrollPrimary + " " + scrollSecondary
1942                        +" " + mWindowAlignment);
1943            }
1944            scrollPrimary -= mScrollOffsetPrimary;
1945            scrollSecondary -= mScrollOffsetSecondary;
1946            deltas[0] = scrollPrimary;
1947            deltas[1] = scrollSecondary;
1948            return true;
1949        }
1950        return false;
1951    }
1952
1953    private void scrollGrid(int scrollPrimary, int scrollSecondary, boolean smooth) {
1954        if (mInLayout) {
1955            scrollDirectionPrimary(scrollPrimary);
1956            scrollDirectionSecondary(scrollSecondary);
1957        } else {
1958            int scrollX;
1959            int scrollY;
1960            if (mOrientation == HORIZONTAL) {
1961                scrollX = scrollPrimary;
1962                scrollY = scrollSecondary;
1963            } else {
1964                scrollX = scrollSecondary;
1965                scrollY = scrollPrimary;
1966            }
1967            if (smooth) {
1968                mBaseGridView.smoothScrollBy(scrollX, scrollY);
1969            } else {
1970                mBaseGridView.scrollBy(scrollX, scrollY);
1971            }
1972        }
1973    }
1974
1975    public void setAnimateChildLayout(boolean animateChildLayout) {
1976        mAnimateChildLayout = animateChildLayout;
1977    }
1978
1979    public boolean isChildLayoutAnimated() {
1980        return mAnimateChildLayout;
1981    }
1982
1983    public void setPruneChild(boolean pruneChild) {
1984        if (mPruneChild != pruneChild) {
1985            mPruneChild = pruneChild;
1986            if (mPruneChild) {
1987                requestLayout();
1988            }
1989        }
1990    }
1991
1992    public boolean getPruneChild() {
1993        return mPruneChild;
1994    }
1995
1996    private int findImmediateChildIndex(View view) {
1997        while (view != null && view != mBaseGridView) {
1998            int index = mBaseGridView.indexOfChild(view);
1999            if (index >= 0) {
2000                return index;
2001            }
2002            view = (View) view.getParent();
2003        }
2004        return NO_POSITION;
2005    }
2006
2007    void setFocusSearchDisabled(boolean disabled) {
2008        mFocusSearchDisabled = disabled;
2009    }
2010
2011    boolean isFocusSearchDisabled() {
2012        return mFocusSearchDisabled;
2013    }
2014
2015    @Override
2016    public View onInterceptFocusSearch(View focused, int direction) {
2017        if (mFocusSearchDisabled) {
2018            return focused;
2019        }
2020        return null;
2021    }
2022
2023    boolean hasNextViewInSameRow(int pos) {
2024        if (mGrid == null || pos == NO_POSITION) {
2025            return false;
2026        }
2027        final int focusedRow = mGrid.getLocation(pos).row;
2028        for (int i = 0, count = getChildCount(); i < count; i++) {
2029            int position = getPositionByIndex(i);
2030            StaggeredGrid.Location loc = mGrid.getLocation(position);
2031            if (loc != null && loc.row == focusedRow) {
2032                if (position > pos) {
2033                    return true;
2034                }
2035            }
2036        }
2037        return false;
2038    }
2039
2040    boolean hasPreviousViewInSameRow(int pos) {
2041        if (mGrid == null || pos == NO_POSITION) {
2042            return false;
2043        }
2044        final int focusedRow = mGrid.getLocation(pos).row;
2045        for (int i = getChildCount() - 1; i >= 0; i--) {
2046            int position = getPositionByIndex(i);
2047            StaggeredGrid.Location loc = mGrid.getLocation(position);
2048            if (loc != null && loc.row == focusedRow) {
2049                if (position < pos) {
2050                    return true;
2051                }
2052            }
2053        }
2054        return false;
2055    }
2056
2057    @Override
2058    public boolean onAddFocusables(RecyclerView recyclerView,
2059            ArrayList<View> views, int direction, int focusableMode) {
2060        if (mFocusSearchDisabled) {
2061            return true;
2062        }
2063        // If this viewgroup or one of its children currently has focus then we
2064        // consider our children for focus searching in main direction on the same row.
2065        // If this viewgroup has no focus and using focus align, we want the system
2066        // to ignore our children and pass focus to the viewgroup, which will pass
2067        // focus on to its children appropriately.
2068        // If this viewgroup has no focus and not using focus align, we want to
2069        // consider the child that does not overlap with padding area.
2070        if (recyclerView.hasFocus()) {
2071            final int movement = getMovement(direction);
2072            if (movement != PREV_ITEM && movement != NEXT_ITEM) {
2073                // Move on secondary direction uses default addFocusables().
2074                return false;
2075            }
2076            final View focused = recyclerView.findFocus();
2077            final int focusedPos = getPositionByIndex(findImmediateChildIndex(focused));
2078            // Add focusables of focused item.
2079            if (focusedPos != NO_POSITION) {
2080                findViewByPosition(focusedPos).addFocusables(views,  direction, focusableMode);
2081            }
2082            final int focusedRow = mGrid != null && focusedPos != NO_POSITION ?
2083                    mGrid.getLocation(focusedPos).row : NO_POSITION;
2084            // Add focusables of next neighbor of same row on the focus search direction.
2085            if (mGrid != null) {
2086                final int focusableCount = views.size();
2087                for (int i = 0, count = getChildCount(); i < count; i++) {
2088                    int index = movement == NEXT_ITEM ? i : count - 1 - i;
2089                    final View child = getChildAt(index);
2090                    if (child.getVisibility() != View.VISIBLE) {
2091                        continue;
2092                    }
2093                    int position = getPositionByIndex(index);
2094                    StaggeredGrid.Location loc = mGrid.getLocation(position);
2095                    if (focusedRow == NO_POSITION || (loc != null && loc.row == focusedRow)) {
2096                        if (focusedPos == NO_POSITION ||
2097                                (movement == NEXT_ITEM && position > focusedPos)
2098                                || (movement == PREV_ITEM && position < focusedPos)) {
2099                            child.addFocusables(views,  direction, focusableMode);
2100                            if (views.size() > focusableCount) {
2101                                break;
2102                            }
2103                        }
2104                    }
2105                }
2106            }
2107        } else {
2108            if (mFocusScrollStrategy != BaseGridView.FOCUS_SCROLL_ALIGNED) {
2109                // adding views not overlapping padding area to avoid scrolling in gaining focus
2110                int left = mWindowAlignment.mainAxis().getPaddingLow();
2111                int right = mWindowAlignment.mainAxis().getClientSize() + left;
2112                int focusableCount = views.size();
2113                for (int i = 0, count = getChildCount(); i < count; i++) {
2114                    View child = getChildAt(i);
2115                    if (child.getVisibility() == View.VISIBLE) {
2116                        if (getViewMin(child) >= left && getViewMax(child) <= right) {
2117                            child.addFocusables(views, direction, focusableMode);
2118                        }
2119                    }
2120                }
2121                // if we cannot find any, then just add all children.
2122                if (views.size() == focusableCount) {
2123                    for (int i = 0, count = getChildCount(); i < count; i++) {
2124                        View child = getChildAt(i);
2125                        if (child.getVisibility() == View.VISIBLE) {
2126                            child.addFocusables(views, direction, focusableMode);
2127                        }
2128                    }
2129                    if (views.size() != focusableCount) {
2130                        return true;
2131                    }
2132                } else {
2133                    return true;
2134                }
2135                // if still cannot find any, fall through and add itself
2136            }
2137            if (recyclerView.isFocusable()) {
2138                views.add(recyclerView);
2139            }
2140        }
2141        return true;
2142    }
2143
2144    @Override
2145    public View onFocusSearchFailed(View focused, int direction, Recycler recycler,
2146            RecyclerView.State state) {
2147        if (DEBUG) Log.v(getTag(), "onFocusSearchFailed direction " + direction);
2148
2149        saveContext(recycler, state);
2150        View view = null;
2151        int movement = getMovement(direction);
2152        final FocusFinder ff = FocusFinder.getInstance();
2153        if (movement == NEXT_ITEM) {
2154            while (view == null && !appendOneVisibleItem()) {
2155                view = ff.findNextFocus(mBaseGridView, focused, direction);
2156            }
2157        } else if (movement == PREV_ITEM){
2158            while (view == null && !prependOneVisibleItem()) {
2159                view = ff.findNextFocus(mBaseGridView, focused, direction);
2160            }
2161        }
2162        if (view == null) {
2163            // returning the same view to prevent focus lost when scrolling past the end of the list
2164            if (movement == PREV_ITEM) {
2165                view = mFocusOutFront ? null : focused;
2166            } else if (movement == NEXT_ITEM){
2167                view = mFocusOutEnd ? null : focused;
2168            }
2169        }
2170        leaveContext();
2171        if (DEBUG) Log.v(getTag(), "returning view " + view);
2172        return view;
2173    }
2174
2175    boolean gridOnRequestFocusInDescendants(RecyclerView recyclerView, int direction,
2176            Rect previouslyFocusedRect) {
2177        switch (mFocusScrollStrategy) {
2178        case BaseGridView.FOCUS_SCROLL_ALIGNED:
2179        default:
2180            return gridOnRequestFocusInDescendantsAligned(recyclerView,
2181                    direction, previouslyFocusedRect);
2182        case BaseGridView.FOCUS_SCROLL_PAGE:
2183        case BaseGridView.FOCUS_SCROLL_ITEM:
2184            return gridOnRequestFocusInDescendantsUnaligned(recyclerView,
2185                    direction, previouslyFocusedRect);
2186        }
2187    }
2188
2189    private boolean gridOnRequestFocusInDescendantsAligned(RecyclerView recyclerView,
2190            int direction, Rect previouslyFocusedRect) {
2191        View view = findViewByPosition(mFocusPosition);
2192        if (view != null) {
2193            boolean result = view.requestFocus(direction, previouslyFocusedRect);
2194            if (!result && DEBUG) {
2195                Log.w(getTag(), "failed to request focus on " + view);
2196            }
2197            return result;
2198        }
2199        return false;
2200    }
2201
2202    private boolean gridOnRequestFocusInDescendantsUnaligned(RecyclerView recyclerView,
2203            int direction, Rect previouslyFocusedRect) {
2204        // focus to view not overlapping padding area to avoid scrolling in gaining focus
2205        int index;
2206        int increment;
2207        int end;
2208        int count = getChildCount();
2209        if ((direction & View.FOCUS_FORWARD) != 0) {
2210            index = 0;
2211            increment = 1;
2212            end = count;
2213        } else {
2214            index = count - 1;
2215            increment = -1;
2216            end = -1;
2217        }
2218        int left = mWindowAlignment.mainAxis().getPaddingLow();
2219        int right = mWindowAlignment.mainAxis().getClientSize() + left;
2220        for (int i = index; i != end; i += increment) {
2221            View child = getChildAt(i);
2222            if (child.getVisibility() == View.VISIBLE) {
2223                if (getViewMin(child) >= left && getViewMax(child) <= right) {
2224                    if (child.requestFocus(direction, previouslyFocusedRect)) {
2225                        return true;
2226                    }
2227                }
2228            }
2229        }
2230        return false;
2231    }
2232
2233    private final static int PREV_ITEM = 0;
2234    private final static int NEXT_ITEM = 1;
2235    private final static int PREV_ROW = 2;
2236    private final static int NEXT_ROW = 3;
2237
2238    private int getMovement(int direction) {
2239        int movement = View.FOCUS_LEFT;
2240
2241        if (mOrientation == HORIZONTAL) {
2242            switch(direction) {
2243                case View.FOCUS_LEFT:
2244                    movement = PREV_ITEM;
2245                    break;
2246                case View.FOCUS_RIGHT:
2247                    movement = NEXT_ITEM;
2248                    break;
2249                case View.FOCUS_UP:
2250                    movement = PREV_ROW;
2251                    break;
2252                case View.FOCUS_DOWN:
2253                    movement = NEXT_ROW;
2254                    break;
2255            }
2256         } else if (mOrientation == VERTICAL) {
2257             switch(direction) {
2258                 case View.FOCUS_LEFT:
2259                     movement = PREV_ROW;
2260                     break;
2261                 case View.FOCUS_RIGHT:
2262                     movement = NEXT_ROW;
2263                     break;
2264                 case View.FOCUS_UP:
2265                     movement = PREV_ITEM;
2266                     break;
2267                 case View.FOCUS_DOWN:
2268                     movement = NEXT_ITEM;
2269                     break;
2270             }
2271         }
2272
2273        return movement;
2274    }
2275
2276    int getChildDrawingOrder(RecyclerView recyclerView, int childCount, int i) {
2277        View view = findViewByPosition(mFocusPosition);
2278        if (view == null) {
2279            return i;
2280        }
2281        int focusIndex = recyclerView.indexOfChild(view);
2282        // supposely 0 1 2 3 4 5 6 7 8 9, 4 is the center item
2283        // drawing order is 0 1 2 3 9 8 7 6 5 4
2284        if (i < focusIndex) {
2285            return i;
2286        } else if (i < childCount - 1) {
2287            return focusIndex + childCount - 1 - i;
2288        } else {
2289            return focusIndex;
2290        }
2291    }
2292
2293    @Override
2294    public void onAdapterChanged(RecyclerView.Adapter oldAdapter,
2295            RecyclerView.Adapter newAdapter) {
2296        discardLayoutInfo();
2297        super.onAdapterChanged(oldAdapter, newAdapter);
2298    }
2299
2300    private void discardLayoutInfo() {
2301        mGrid = null;
2302        mRows = null;
2303        mRowSizeSecondary = null;
2304        mFirstVisiblePos = -1;
2305        mLastVisiblePos = -1;
2306        mRowSecondarySizeRefresh = false;
2307    }
2308
2309    public void setLayoutEnabled(boolean layoutEnabled) {
2310        if (mLayoutEnabled != layoutEnabled) {
2311            mLayoutEnabled = layoutEnabled;
2312            requestLayout();
2313        }
2314    }
2315}
2316