GridLayoutManager.java revision 08a42433300b4617bad27bda1214e12ca7854adc
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     * True if prune child,  might be disabled during transition.
328     */
329    private boolean mPruneChild = true;
330
331    private int[] mTempDeltas = new int[2];
332
333    private boolean mUseDeltaInPreLayout;
334
335    private int mDeltaInPreLayout, mDeltaSecondaryInPreLayout;
336
337    /**
338     * Temporaries used for measuring.
339     */
340    private int[] mMeasuredDimension = new int[2];
341
342    public GridLayoutManager(BaseGridView baseGridView) {
343        mBaseGridView = baseGridView;
344    }
345
346    public void setOrientation(int orientation) {
347        if (orientation != HORIZONTAL && orientation != VERTICAL) {
348            if (DEBUG) Log.v(getTag(), "invalid orientation: " + orientation);
349            return;
350        }
351
352        mOrientation = orientation;
353        mWindowAlignment.setOrientation(orientation);
354        mItemAlignment.setOrientation(orientation);
355        mForceFullLayout = true;
356    }
357
358    public int getFocusScrollStrategy() {
359        return mFocusScrollStrategy;
360    }
361
362    public void setFocusScrollStrategy(int focusScrollStrategy) {
363        mFocusScrollStrategy = focusScrollStrategy;
364    }
365
366    public void setWindowAlignment(int windowAlignment) {
367        mWindowAlignment.mainAxis().setWindowAlignment(windowAlignment);
368    }
369
370    public int getWindowAlignment() {
371        return mWindowAlignment.mainAxis().getWindowAlignment();
372    }
373
374    public void setWindowAlignmentOffset(int alignmentOffset) {
375        mWindowAlignment.mainAxis().setWindowAlignmentOffset(alignmentOffset);
376    }
377
378    public int getWindowAlignmentOffset() {
379        return mWindowAlignment.mainAxis().getWindowAlignmentOffset();
380    }
381
382    public void setWindowAlignmentOffsetPercent(float offsetPercent) {
383        mWindowAlignment.mainAxis().setWindowAlignmentOffsetPercent(offsetPercent);
384    }
385
386    public float getWindowAlignmentOffsetPercent() {
387        return mWindowAlignment.mainAxis().getWindowAlignmentOffsetPercent();
388    }
389
390    public void setItemAlignmentOffset(int alignmentOffset) {
391        mItemAlignment.mainAxis().setItemAlignmentOffset(alignmentOffset);
392        updateChildAlignments();
393    }
394
395    public int getItemAlignmentOffset() {
396        return mItemAlignment.mainAxis().getItemAlignmentOffset();
397    }
398
399    public void setItemAlignmentOffsetWithPadding(boolean withPadding) {
400        mItemAlignment.mainAxis().setItemAlignmentOffsetWithPadding(withPadding);
401        updateChildAlignments();
402    }
403
404    public boolean isItemAlignmentOffsetWithPadding() {
405        return mItemAlignment.mainAxis().isItemAlignmentOffsetWithPadding();
406    }
407
408    public void setItemAlignmentOffsetPercent(float offsetPercent) {
409        mItemAlignment.mainAxis().setItemAlignmentOffsetPercent(offsetPercent);
410        updateChildAlignments();
411    }
412
413    public float getItemAlignmentOffsetPercent() {
414        return mItemAlignment.mainAxis().getItemAlignmentOffsetPercent();
415    }
416
417    public void setItemAlignmentViewId(int viewId) {
418        mItemAlignment.mainAxis().setItemAlignmentViewId(viewId);
419        updateChildAlignments();
420    }
421
422    public int getItemAlignmentViewId() {
423        return mItemAlignment.mainAxis().getItemAlignmentViewId();
424    }
425
426    public void setFocusOutAllowed(boolean throughFront, boolean throughEnd) {
427        mFocusOutFront = throughFront;
428        mFocusOutEnd = throughEnd;
429    }
430
431    public void setNumRows(int numRows) {
432        if (numRows < 0) throw new IllegalArgumentException();
433        mNumRowsRequested = numRows;
434        mForceFullLayout = true;
435    }
436
437    /**
438     * Set the row height. May be WRAP_CONTENT, or a size in pixels.
439     */
440    public void setRowHeight(int height) {
441        if (height >= 0 || height == ViewGroup.LayoutParams.WRAP_CONTENT) {
442            mRowSizeSecondaryRequested = height;
443        } else {
444            throw new IllegalArgumentException("Invalid row height: " + height);
445        }
446    }
447
448    public void setItemMargin(int margin) {
449        mVerticalMargin = mHorizontalMargin = margin;
450        mMarginPrimary = mMarginSecondary = margin;
451    }
452
453    public void setVerticalMargin(int margin) {
454        if (mOrientation == HORIZONTAL) {
455            mMarginSecondary = mVerticalMargin = margin;
456        } else {
457            mMarginPrimary = mVerticalMargin = margin;
458        }
459    }
460
461    public void setHorizontalMargin(int margin) {
462        if (mOrientation == HORIZONTAL) {
463            mMarginPrimary = mHorizontalMargin = margin;
464        } else {
465            mMarginSecondary = mHorizontalMargin = margin;
466        }
467    }
468
469    public int getVerticalMargin() {
470        return mVerticalMargin;
471    }
472
473    public int getHorizontalMargin() {
474        return mHorizontalMargin;
475    }
476
477    public void setGravity(int gravity) {
478        mGravity = gravity;
479    }
480
481    protected boolean hasDoneFirstLayout() {
482        return mGrid != null;
483    }
484
485    public void setOnChildSelectedListener(OnChildSelectedListener listener) {
486        mChildSelectedListener = listener;
487    }
488
489    private int getPositionByView(View view) {
490        if (view == null) {
491            return NO_POSITION;
492        }
493        LayoutParams params = (LayoutParams) view.getLayoutParams();
494        if (params == null || params.isItemRemoved()) {
495            // when item is removed, the position value can be any value.
496            return NO_POSITION;
497        }
498        return params.getViewPosition();
499    }
500
501    private int getPositionByIndex(int index) {
502        return getPositionByView(getChildAt(index));
503    }
504
505    private void dispatchChildSelected() {
506        if (mChildSelectedListener == null) {
507            return;
508        }
509        if (mFocusPosition != NO_POSITION) {
510            View view = findViewByPosition(mFocusPosition);
511            if (view != null) {
512                RecyclerView.ViewHolder vh = mBaseGridView.getChildViewHolder(view);
513                mChildSelectedListener.onChildSelected(mBaseGridView, view, mFocusPosition,
514                        vh == null? NO_ID: vh.getItemId());
515                return;
516            }
517        }
518        mChildSelectedListener.onChildSelected(mBaseGridView, null, NO_POSITION, NO_ID);
519    }
520
521    @Override
522    public boolean canScrollHorizontally() {
523        // We can scroll horizontally if we have horizontal orientation, or if
524        // we are vertical and have more than one column.
525        return mOrientation == HORIZONTAL || mNumRows > 1;
526    }
527
528    @Override
529    public boolean canScrollVertically() {
530        // We can scroll vertically if we have vertical orientation, or if we
531        // are horizontal and have more than one row.
532        return mOrientation == VERTICAL || mNumRows > 1;
533    }
534
535    @Override
536    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
537        return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
538                ViewGroup.LayoutParams.WRAP_CONTENT);
539    }
540
541    @Override
542    public RecyclerView.LayoutParams generateLayoutParams(Context context, AttributeSet attrs) {
543        return new LayoutParams(context, attrs);
544    }
545
546    @Override
547    public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
548        if (lp instanceof LayoutParams) {
549            return new LayoutParams((LayoutParams) lp);
550        } else if (lp instanceof RecyclerView.LayoutParams) {
551            return new LayoutParams((RecyclerView.LayoutParams) lp);
552        } else if (lp instanceof MarginLayoutParams) {
553            return new LayoutParams((MarginLayoutParams) lp);
554        } else {
555            return new LayoutParams(lp);
556        }
557    }
558
559    protected View getViewForPosition(int position) {
560        return mRecycler.getViewForPosition(position);
561    }
562
563    final int getOpticalLeft(View v) {
564        return ((LayoutParams) v.getLayoutParams()).getOpticalLeft(v);
565    }
566
567    final int getOpticalRight(View v) {
568        return ((LayoutParams) v.getLayoutParams()).getOpticalRight(v);
569    }
570
571    final int getOpticalTop(View v) {
572        return ((LayoutParams) v.getLayoutParams()).getOpticalTop(v);
573    }
574
575    final int getOpticalBottom(View v) {
576        return ((LayoutParams) v.getLayoutParams()).getOpticalBottom(v);
577    }
578
579    private int getViewMin(View v) {
580        return (mOrientation == HORIZONTAL) ? getOpticalLeft(v) : getOpticalTop(v);
581    }
582
583    private int getViewMax(View v) {
584        return (mOrientation == HORIZONTAL) ? getOpticalRight(v) : getOpticalBottom(v);
585    }
586
587    private int getViewCenter(View view) {
588        return (mOrientation == HORIZONTAL) ? getViewCenterX(view) : getViewCenterY(view);
589    }
590
591    private int getViewCenterSecondary(View view) {
592        return (mOrientation == HORIZONTAL) ? getViewCenterY(view) : getViewCenterX(view);
593    }
594
595    private int getViewCenterX(View v) {
596        LayoutParams p = (LayoutParams) v.getLayoutParams();
597        return p.getOpticalLeft(v) + p.getAlignX();
598    }
599
600    private int getViewCenterY(View v) {
601        LayoutParams p = (LayoutParams) v.getLayoutParams();
602        return p.getOpticalTop(v) + p.getAlignY();
603    }
604
605    /**
606     * Save Recycler and State for convenience.  Must be paired with leaveContext().
607     */
608    private void saveContext(Recycler recycler, State state) {
609        if (mRecycler != null || mState != null) {
610            Log.e(TAG, "Recycler information was not released, bug!");
611        }
612        mRecycler = recycler;
613        mState = state;
614    }
615
616    /**
617     * Discard saved Recycler and State.
618     */
619    private void leaveContext() {
620        mRecycler = null;
621        mState = null;
622    }
623
624    /**
625     * Re-initialize data structures for a data change or handling invisible
626     * selection. The method tries its best to preserve position information so
627     * that staggered grid looks same before and after re-initialize.
628     * @param focusPosition The initial focusPosition that we would like to
629     *        focus on.
630     * @return Actual position that can be focused on.
631     */
632    private int init(int focusPosition) {
633
634        final int newItemCount = mState.getItemCount();
635
636        if (focusPosition == NO_POSITION && newItemCount > 0) {
637            // if focus position is never set before,  initialize it to 0
638            focusPosition = 0;
639        }
640        // If adapter has changed then caches are invalid; otherwise,
641        // we try to maintain each row's position if number of rows keeps the same
642        // and existing mGrid contains the focusPosition.
643        if (mRows != null && mNumRows == mRows.length &&
644                mGrid != null && mGrid.getSize() > 0 && focusPosition >= 0 &&
645                focusPosition >= mGrid.getFirstIndex() &&
646                focusPosition <= mGrid.getLastIndex()) {
647            // strip mGrid to a subset (like a column) that contains focusPosition
648            mGrid.stripDownTo(focusPosition);
649            // make sure that remaining items do not exceed new adapter size
650            int firstIndex = mGrid.getFirstIndex();
651            int lastIndex = mGrid.getLastIndex();
652            if (DEBUG) {
653                Log .v(getTag(), "mGrid firstIndex " + firstIndex + " lastIndex " + lastIndex);
654            }
655            for (int i = lastIndex; i >=firstIndex; i--) {
656                if (i >= newItemCount) {
657                    mGrid.removeLast();
658                }
659            }
660            if (mGrid.getSize() == 0) {
661                focusPosition = newItemCount - 1;
662                // initialize row start locations
663                for (int i = 0; i < mNumRows; i++) {
664                    mRows[i].low = 0;
665                    mRows[i].high = 0;
666                }
667                if (DEBUG) Log.v(getTag(), "mGrid zero size");
668            } else {
669                // initialize row start locations
670                for (int i = 0; i < mNumRows; i++) {
671                    mRows[i].low = Integer.MAX_VALUE;
672                    mRows[i].high = Integer.MIN_VALUE;
673                }
674                firstIndex = mGrid.getFirstIndex();
675                lastIndex = mGrid.getLastIndex();
676                if (focusPosition > lastIndex) {
677                    focusPosition = mGrid.getLastIndex();
678                }
679                if (DEBUG) {
680                    Log.v(getTag(), "mGrid firstIndex " + firstIndex + " lastIndex "
681                        + lastIndex + " focusPosition " + focusPosition);
682                }
683                // fill rows with minimal view positions of the subset
684                for (int i = firstIndex; i <= lastIndex; i++) {
685                    View v = findViewByPosition(i);
686                    if (v == null) {
687                        continue;
688                    }
689                    int row = mGrid.getLocation(i).row;
690                    int low = getViewMin(v) + mScrollOffsetPrimary;
691                    if (low < mRows[row].low) {
692                        mRows[row].low = mRows[row].high = low;
693                    }
694                }
695                int firstItemRowPosition = mRows[mGrid.getLocation(firstIndex).row].low;
696                if (firstItemRowPosition == Integer.MAX_VALUE) {
697                    firstItemRowPosition = 0;
698                }
699                if (mState.didStructureChange()) {
700                    // if there is structure change, the removed item might be in the
701                    // subset,  so it is meaningless to maintain the low locations.
702                    for (int i = 0; i < mNumRows; i++) {
703                        mRows[i].low = firstItemRowPosition;
704                        mRows[i].high = firstItemRowPosition;
705                    }
706                } else {
707                    // fill other rows that does not include the subset using first item
708                    for (int i = 0; i < mNumRows; i++) {
709                        if (mRows[i].low == Integer.MAX_VALUE) {
710                            mRows[i].low = mRows[i].high = firstItemRowPosition;
711                        }
712                    }
713                }
714            }
715
716            // Same adapter, we can reuse any attached views
717            detachAndScrapAttachedViews(mRecycler);
718
719        } else {
720            // otherwise recreate data structure
721            mRows = new StaggeredGrid.Row[mNumRows];
722
723            for (int i = 0; i < mNumRows; i++) {
724                mRows[i] = new StaggeredGrid.Row();
725            }
726            mGrid = new StaggeredGridDefault();
727            if (newItemCount == 0) {
728                focusPosition = NO_POSITION;
729            } else if (focusPosition >= newItemCount) {
730                focusPosition = newItemCount - 1;
731            }
732
733            // Adapter may have changed so remove all attached views permanently
734            removeAndRecycleAllViews(mRecycler);
735
736            mScrollOffsetPrimary = 0;
737            mScrollOffsetSecondary = 0;
738            mWindowAlignment.reset();
739        }
740
741        mGrid.setProvider(mGridProvider);
742        // mGrid share the same Row array information
743        mGrid.setRows(mRows);
744        mFirstVisiblePos = mLastVisiblePos = NO_POSITION;
745
746        initScrollController();
747        updateScrollSecondAxis();
748
749        return focusPosition;
750    }
751
752    private int getRowSizeSecondary(int rowIndex) {
753        if (mFixedRowSizeSecondary != 0) {
754            return mFixedRowSizeSecondary;
755        }
756        if (mRowSizeSecondary == null) {
757            return 0;
758        }
759        return mRowSizeSecondary[rowIndex];
760    }
761
762    private int getRowStartSecondary(int rowIndex) {
763        int start = 0;
764        for (int i = 0; i < rowIndex; i++) {
765            start += getRowSizeSecondary(i) + mMarginSecondary;
766        }
767        return start;
768    }
769
770    private int getSizeSecondary() {
771        return getRowStartSecondary(mNumRows - 1) + getRowSizeSecondary(mNumRows - 1);
772    }
773
774    private void measureScrapChild(int position, int widthSpec, int heightSpec,
775            int[] measuredDimension) {
776        View view = mRecycler.getViewForPosition(position);
777        if (view != null) {
778            LayoutParams p = (LayoutParams) view.getLayoutParams();
779            int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
780                    getPaddingLeft() + getPaddingRight(), p.width);
781            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
782                    getPaddingTop() + getPaddingBottom(), p.height);
783            view.measure(childWidthSpec, childHeightSpec);
784            measuredDimension[0] = view.getMeasuredWidth();
785            measuredDimension[1] = view.getMeasuredHeight();
786            mRecycler.recycleView(view);
787        }
788    }
789
790    private boolean processRowSizeSecondary(boolean measure) {
791        if (mFixedRowSizeSecondary != 0) {
792            return false;
793        }
794
795        if (mGrid == null) {
796            if (mState.getItemCount() > 0) {
797                measureScrapChild(mFocusPosition == NO_POSITION ? 0 : mFocusPosition,
798                        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
799                        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
800                        mMeasuredDimension);
801                if (DEBUG) Log.v(TAG, "measured scrap child: " + mMeasuredDimension[0] +
802                        " " + mMeasuredDimension[1]);
803            } else {
804                mMeasuredDimension[0] = mMeasuredDimension[1] = 0;
805            }
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                    mMeasuredDimension[0] = view.getMeasuredWidth();
827                    mMeasuredDimension[1] = view.getMeasuredHeight();
828                }
829                final int secondarySize = mOrientation == HORIZONTAL ?
830                        mMeasuredDimension[1] : mMeasuredDimension[0];
831                if (secondarySize > rowSize) {
832                    rowSize = secondarySize;
833                }
834            }
835            if (DEBUG) Log.v(getTag(), "row " + rowIndex + " rowItemCount " + rowItemCount +
836                    " rowSize " + rowSize);
837
838            if (mRowSizeSecondary[rowIndex] != rowSize) {
839                if (DEBUG) Log.v(getTag(), "row size secondary changed: " + mRowSizeSecondary[rowIndex] +
840                        ", " + rowSize);
841
842                mRowSizeSecondary[rowIndex] = rowSize;
843                changed = true;
844            }
845        }
846
847        return changed;
848    }
849
850    /**
851     * Checks if we need to update row secondary sizes.
852     */
853    private void updateRowSecondarySizeRefresh() {
854        mRowSecondarySizeRefresh = processRowSizeSecondary(false);
855        if (mRowSecondarySizeRefresh) {
856            if (DEBUG) Log.v(getTag(), "mRowSecondarySizeRefresh now set");
857            forceRequestLayout();
858        }
859    }
860
861    private void forceRequestLayout() {
862        if (DEBUG) Log.v(getTag(), "forceRequestLayout");
863        // RecyclerView prevents us from requesting layout in many cases
864        // (during layout, during scroll, etc.)
865        // For secondary row size wrap_content support we currently need a
866        // second layout pass to update the measured size after having measured
867        // and added child views in layoutChildren.
868        // Force the second layout by posting a delayed runnable.
869        // TODO: investigate allowing a second layout pass,
870        // or move child add/measure logic to the measure phase.
871        mBaseGridView.getHandler().post(new Runnable() {
872           @Override
873           public void run() {
874               if (DEBUG) Log.v(getTag(), "request Layout from runnable");
875               requestLayout();
876           }
877        });
878    }
879
880    @Override
881    public void onMeasure(Recycler recycler, State state, int widthSpec, int heightSpec) {
882        saveContext(recycler, state);
883
884        int sizePrimary, sizeSecondary, modeSecondary, paddingSecondary;
885        int measuredSizeSecondary;
886        if (mOrientation == HORIZONTAL) {
887            sizePrimary = MeasureSpec.getSize(widthSpec);
888            sizeSecondary = MeasureSpec.getSize(heightSpec);
889            modeSecondary = MeasureSpec.getMode(heightSpec);
890            paddingSecondary = getPaddingTop() + getPaddingBottom();
891        } else {
892            sizeSecondary = MeasureSpec.getSize(widthSpec);
893            sizePrimary = MeasureSpec.getSize(heightSpec);
894            modeSecondary = MeasureSpec.getMode(widthSpec);
895            paddingSecondary = getPaddingLeft() + getPaddingRight();
896        }
897        if (DEBUG) Log.v(getTag(), "onMeasure widthSpec " + Integer.toHexString(widthSpec) +
898                " heightSpec " + Integer.toHexString(heightSpec) +
899                " modeSecondary " + Integer.toHexString(modeSecondary) +
900                " sizeSecondary " + sizeSecondary + " " + this);
901
902        mMaxSizeSecondary = sizeSecondary;
903
904        if (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) {
905            mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested;
906            mFixedRowSizeSecondary = 0;
907
908            if (mRowSizeSecondary == null || mRowSizeSecondary.length != mNumRows) {
909                mRowSizeSecondary = new int[mNumRows];
910            }
911
912            // Measure all current children and update cached row heights
913            processRowSizeSecondary(true);
914
915            switch (modeSecondary) {
916            case MeasureSpec.UNSPECIFIED:
917                measuredSizeSecondary = getSizeSecondary() + paddingSecondary;
918                break;
919            case MeasureSpec.AT_MOST:
920                measuredSizeSecondary = Math.min(getSizeSecondary() + paddingSecondary,
921                        mMaxSizeSecondary);
922                break;
923            case MeasureSpec.EXACTLY:
924                measuredSizeSecondary = mMaxSizeSecondary;
925                break;
926            default:
927                throw new IllegalStateException("wrong spec");
928            }
929
930        } else {
931            switch (modeSecondary) {
932            case MeasureSpec.UNSPECIFIED:
933                if (mRowSizeSecondaryRequested == 0) {
934                    if (mOrientation == HORIZONTAL) {
935                        throw new IllegalStateException("Must specify rowHeight or view height");
936                    } else {
937                        throw new IllegalStateException("Must specify columnWidth or view width");
938                    }
939                }
940                mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
941                mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested;
942                measuredSizeSecondary = mFixedRowSizeSecondary * mNumRows + mMarginSecondary
943                    * (mNumRows - 1) + paddingSecondary;
944                break;
945            case MeasureSpec.AT_MOST:
946            case MeasureSpec.EXACTLY:
947                if (mNumRowsRequested == 0 && mRowSizeSecondaryRequested == 0) {
948                    mNumRows = 1;
949                    mFixedRowSizeSecondary = sizeSecondary - paddingSecondary;
950                } else if (mNumRowsRequested == 0) {
951                    mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
952                    mNumRows = (sizeSecondary + mMarginSecondary)
953                        / (mRowSizeSecondaryRequested + mMarginSecondary);
954                } else if (mRowSizeSecondaryRequested == 0) {
955                    mNumRows = mNumRowsRequested;
956                    mFixedRowSizeSecondary = (sizeSecondary - paddingSecondary - mMarginSecondary
957                            * (mNumRows - 1)) / mNumRows;
958                } else {
959                    mNumRows = mNumRowsRequested;
960                    mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
961                }
962                measuredSizeSecondary = sizeSecondary;
963                if (modeSecondary == MeasureSpec.AT_MOST) {
964                    int childrenSize = mFixedRowSizeSecondary * mNumRows + mMarginSecondary
965                        * (mNumRows - 1) + paddingSecondary;
966                    if (childrenSize < measuredSizeSecondary) {
967                        measuredSizeSecondary = childrenSize;
968                    }
969                }
970                break;
971            default:
972                throw new IllegalStateException("wrong spec");
973            }
974        }
975        if (mOrientation == HORIZONTAL) {
976            setMeasuredDimension(sizePrimary, measuredSizeSecondary);
977        } else {
978            setMeasuredDimension(measuredSizeSecondary, sizePrimary);
979        }
980        if (DEBUG) {
981            Log.v(getTag(), "onMeasure sizePrimary " + sizePrimary +
982                    " measuredSizeSecondary " + measuredSizeSecondary +
983                    " mFixedRowSizeSecondary " + mFixedRowSizeSecondary +
984                    " mNumRows " + mNumRows);
985        }
986
987        leaveContext();
988    }
989
990    private void measureChild(View child) {
991        final ViewGroup.LayoutParams lp = child.getLayoutParams();
992        final int secondarySpec = (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) ?
993                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) :
994                MeasureSpec.makeMeasureSpec(mFixedRowSizeSecondary, MeasureSpec.EXACTLY);
995        int widthSpec, heightSpec;
996
997        if (mOrientation == HORIZONTAL) {
998            widthSpec = ViewGroup.getChildMeasureSpec(
999                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
1000                    0, lp.width);
1001            heightSpec = ViewGroup.getChildMeasureSpec(secondarySpec, 0, lp.height);
1002        } else {
1003            heightSpec = ViewGroup.getChildMeasureSpec(
1004                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
1005                    0, lp.height);
1006            widthSpec = ViewGroup.getChildMeasureSpec(secondarySpec, 0, lp.width);
1007        }
1008
1009        child.measure(widthSpec, heightSpec);
1010
1011        if (DEBUG) Log.v(getTag(), "measureChild secondarySpec " + Integer.toHexString(secondarySpec) +
1012                " widthSpec " + Integer.toHexString(widthSpec) +
1013                " heightSpec " + Integer.toHexString(heightSpec) +
1014                " measuredWidth " + child.getMeasuredWidth() +
1015                " measuredHeight " + child.getMeasuredHeight());
1016        if (DEBUG) Log.v(getTag(), "child lp width " + lp.width + " height " + lp.height);
1017    }
1018
1019    private StaggeredGrid.Provider mGridProvider = new StaggeredGrid.Provider() {
1020
1021        @Override
1022        public int getCount() {
1023            return mState.getItemCount();
1024        }
1025
1026        @Override
1027        public void createItem(int index, int rowIndex, boolean append) {
1028            View v = getViewForPosition(index);
1029            if (mFirstVisiblePos >= 0) {
1030                // when StaggeredGrid append or prepend item, we must guarantee
1031                // that sibling item has created views already.
1032                if (append && index != mLastVisiblePos + 1) {
1033                    throw new RuntimeException();
1034                } else if (!append && index != mFirstVisiblePos - 1) {
1035                    throw new RuntimeException();
1036                }
1037            }
1038
1039            // See recyclerView docs:  we don't need re-add scraped view if it was removed.
1040            if (!((RecyclerView.LayoutParams) v.getLayoutParams()).isItemRemoved()) {
1041                if (append) {
1042                    addView(v);
1043                } else {
1044                    addView(v, 0);
1045                }
1046                measureChild(v);
1047            }
1048
1049            int length = mOrientation == HORIZONTAL ? v.getMeasuredWidth() : v.getMeasuredHeight();
1050            int start, end;
1051            if (append) {
1052                start = mRows[rowIndex].high;
1053                if (start != mRows[rowIndex].low) {
1054                    // if there are existing item in the row,  add margin between
1055                    start += mMarginPrimary;
1056                } else {
1057                    final int lastRow = mRows.length - 1;
1058                    if (lastRow != rowIndex && mRows[lastRow].high != mRows[lastRow].low) {
1059                        // if there are existing item in the last row, insert
1060                        // the new item after the last item of last row.
1061                        start = mRows[lastRow].high + mMarginPrimary;
1062                    }
1063                }
1064                end = start + length;
1065                mRows[rowIndex].high = end;
1066            } else {
1067                end = mRows[rowIndex].low;
1068                if (end != mRows[rowIndex].high) {
1069                    end -= mMarginPrimary;
1070                } else if (0 != rowIndex && mRows[0].high != mRows[0].low) {
1071                    // if there are existing item in the first row, insert
1072                    // the new item before the first item of first row.
1073                    end = mRows[0].low - mMarginPrimary;
1074                }
1075                start = end - length;
1076                mRows[rowIndex].low = start;
1077            }
1078            if (mFirstVisiblePos < 0) {
1079                mFirstVisiblePos = mLastVisiblePos = index;
1080            } else {
1081                if (append) {
1082                    mLastVisiblePos++;
1083                } else {
1084                    mFirstVisiblePos--;
1085                }
1086            }
1087            if (DEBUG) Log.v(getTag(), "start " + start + " end " + end);
1088            int startSecondary = getRowStartSecondary(rowIndex) - mScrollOffsetSecondary;
1089            layoutChild(rowIndex, v, start - mScrollOffsetPrimary, end - mScrollOffsetPrimary,
1090                    startSecondary);
1091            if (DEBUG) {
1092                Log.d(getTag(), "addView " + index + " " + v);
1093            }
1094            if (index == mFirstVisiblePos) {
1095                updateScrollMin();
1096            }
1097            if (index == mLastVisiblePos) {
1098                updateScrollMax();
1099            }
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    private void removeAndRecycleAllViews(RecyclerView.Recycler recycler) {
1384        if (DEBUG) Log.v(TAG, "removeAndRecycleAllViews " + getChildCount());
1385        for (int i = getChildCount() - 1; i >= 0; i--) {
1386            removeAndRecycleViewAt(i, recycler);
1387        }
1388    }
1389
1390    // Lays out items based on the current scroll position
1391    @Override
1392    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
1393        if (DEBUG) {
1394            Log.v(getTag(), "layoutChildren start numRows " + mNumRows + " mScrollOffsetSecondary "
1395                    + mScrollOffsetSecondary + " mScrollOffsetPrimary " + mScrollOffsetPrimary
1396                    + " inPreLayout " + state.isPreLayout()
1397                    + " didStructureChange " + state.didStructureChange()
1398                    + " mForceFullLayout " + mForceFullLayout);
1399            Log.v(getTag(), "width " + getWidth() + " height " + getHeight());
1400        }
1401
1402        if (mNumRows == 0) {
1403            // haven't done measure yet
1404            return;
1405        }
1406        final int itemCount = state.getItemCount();
1407        if (itemCount < 0) {
1408            return;
1409        }
1410
1411        if (!mLayoutEnabled) {
1412            discardLayoutInfo();
1413            removeAndRecycleAllViews(recycler);
1414            return;
1415        }
1416        mInLayout = true;
1417
1418        saveContext(recycler, state);
1419        // Track the old focus view so we can adjust our system scroll position
1420        // so that any scroll animations happening now will remain valid.
1421        // We must use same delta in Pre Layout (if prelayout exists) and second layout.
1422        // So we cache the deltas in PreLayout and use it in second layout.
1423        int delta = 0, deltaSecondary = 0;
1424        if (!state.isPreLayout() && mUseDeltaInPreLayout) {
1425            delta = mDeltaInPreLayout;
1426            deltaSecondary = mDeltaSecondaryInPreLayout;
1427        } else {
1428            if (mFocusPosition != NO_POSITION
1429                    && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
1430                // FIXME: we should get the remaining scroll animation offset from RecyclerView
1431                View focusView = findViewByPosition(mFocusPosition);
1432                if (focusView != null) {
1433                    delta = mWindowAlignment.mainAxis().getSystemScrollPos(mScrollOffsetPrimary
1434                            + getViewCenter(focusView), false, false) - mScrollOffsetPrimary;
1435                    deltaSecondary = mWindowAlignment.secondAxis().getSystemScrollPos(
1436                            mScrollOffsetSecondary + getViewCenterSecondary(focusView),
1437                            false, false) - mScrollOffsetSecondary;
1438                    if (mUseDeltaInPreLayout = state.isPreLayout()) {
1439                        mDeltaInPreLayout = delta;
1440                        mDeltaSecondaryInPreLayout = deltaSecondary;
1441                    }
1442                }
1443            }
1444        }
1445
1446        final boolean hasDoneFirstLayout = hasDoneFirstLayout();
1447        int savedFocusPos = mFocusPosition;
1448        boolean fastRelayout = false;
1449        if (!mState.didStructureChange() && !mForceFullLayout && hasDoneFirstLayout) {
1450            fastRelayout = true;
1451            fastRelayout();
1452        } else {
1453            boolean hadFocus = mBaseGridView.hasFocus();
1454
1455            int newFocusPosition = init(mFocusPosition);
1456            if (DEBUG) {
1457                Log.v(getTag(), "mFocusPosition " + mFocusPosition + " newFocusPosition "
1458                    + newFocusPosition);
1459            }
1460
1461            // depending on result of init(), either recreating everything
1462            // or try to reuse the row start positions near mFocusPosition
1463            if (mGrid.getSize() == 0) {
1464                // this is a fresh creating all items, starting from
1465                // mFocusPosition with a estimated row index.
1466                mGrid.setStart(newFocusPosition, StaggeredGrid.START_DEFAULT);
1467
1468                // Can't track the old focus view
1469                delta = deltaSecondary = 0;
1470
1471            } else {
1472                // mGrid remembers Locations for the column that
1473                // contains mFocusePosition and also mRows remembers start
1474                // positions of each row.
1475                // Manually re-create child views for that column
1476                int firstIndex = mGrid.getFirstIndex();
1477                int lastIndex = mGrid.getLastIndex();
1478                for (int i = firstIndex; i <= lastIndex; i++) {
1479                    mGridProvider.createItem(i, mGrid.getLocation(i).row, true);
1480                }
1481            }
1482            // add visible views at end until reach the end of window
1483            appendVisibleItems();
1484            // add visible views at front until reach the start of window
1485            prependVisibleItems();
1486            // multiple rounds: scrollToView of first round may drag first/last child into
1487            // "visible window" and we update scrollMin/scrollMax then run second scrollToView
1488            int oldFirstVisible;
1489            int oldLastVisible;
1490            do {
1491                oldFirstVisible = mFirstVisiblePos;
1492                oldLastVisible = mLastVisiblePos;
1493                View focusView = findViewByPosition(newFocusPosition);
1494                // we need force to initialize the child view's position
1495                scrollToView(focusView, false);
1496                if (focusView != null && hadFocus) {
1497                    focusView.requestFocus();
1498                }
1499                appendVisibleItems();
1500                prependVisibleItems();
1501                removeInvisibleViewsAtFront();
1502                removeInvisibleViewsAtEnd();
1503            } while (mFirstVisiblePos != oldFirstVisible || mLastVisiblePos != oldLastVisible);
1504        }
1505        mForceFullLayout = false;
1506
1507        if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
1508            scrollDirectionPrimary(-delta);
1509            scrollDirectionSecondary(-deltaSecondary);
1510        }
1511        appendVisibleItems();
1512        prependVisibleItems();
1513        removeInvisibleViewsAtFront();
1514        removeInvisibleViewsAtEnd();
1515
1516        if (DEBUG) {
1517            StringWriter sw = new StringWriter();
1518            PrintWriter pw = new PrintWriter(sw);
1519            mGrid.debugPrint(pw);
1520            Log.d(getTag(), sw.toString());
1521        }
1522
1523        if (mRowSecondarySizeRefresh) {
1524            mRowSecondarySizeRefresh = false;
1525        } else {
1526            updateRowSecondarySizeRefresh();
1527        }
1528
1529        if (!state.isPreLayout()) {
1530            mUseDeltaInPreLayout = false;
1531            if (!fastRelayout || mFocusPosition != savedFocusPos) {
1532                dispatchChildSelected();
1533            }
1534        }
1535        mInLayout = false;
1536        leaveContext();
1537        if (DEBUG) Log.v(getTag(), "layoutChildren end");
1538    }
1539
1540    private void offsetChildrenSecondary(int increment) {
1541        final int childCount = getChildCount();
1542        if (mOrientation == HORIZONTAL) {
1543            for (int i = 0; i < childCount; i++) {
1544                getChildAt(i).offsetTopAndBottom(increment);
1545            }
1546        } else {
1547            for (int i = 0; i < childCount; i++) {
1548                getChildAt(i).offsetLeftAndRight(increment);
1549            }
1550        }
1551    }
1552
1553    private void offsetChildrenPrimary(int increment) {
1554        final int childCount = getChildCount();
1555        if (mOrientation == VERTICAL) {
1556            for (int i = 0; i < childCount; i++) {
1557                getChildAt(i).offsetTopAndBottom(increment);
1558            }
1559        } else {
1560            for (int i = 0; i < childCount; i++) {
1561                getChildAt(i).offsetLeftAndRight(increment);
1562            }
1563        }
1564    }
1565
1566    @Override
1567    public int scrollHorizontallyBy(int dx, Recycler recycler, RecyclerView.State state) {
1568        if (DEBUG) Log.v(getTag(), "scrollHorizontallyBy " + dx);
1569        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1570            return 0;
1571        }
1572        saveContext(recycler, state);
1573        int result;
1574        if (mOrientation == HORIZONTAL) {
1575            result = scrollDirectionPrimary(dx);
1576        } else {
1577            result = scrollDirectionSecondary(dx);
1578        }
1579        leaveContext();
1580        return result;
1581    }
1582
1583    @Override
1584    public int scrollVerticallyBy(int dy, Recycler recycler, RecyclerView.State state) {
1585        if (DEBUG) Log.v(getTag(), "scrollVerticallyBy " + dy);
1586        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1587            return 0;
1588        }
1589        saveContext(recycler, state);
1590        int result;
1591        if (mOrientation == VERTICAL) {
1592            result = scrollDirectionPrimary(dy);
1593        } else {
1594            result = scrollDirectionSecondary(dy);
1595        }
1596        leaveContext();
1597        return result;
1598    }
1599
1600    // scroll in main direction may add/prune views
1601    private int scrollDirectionPrimary(int da) {
1602        if (da > 0) {
1603            if (!mWindowAlignment.mainAxis().isMaxUnknown()) {
1604                int maxScroll = mWindowAlignment.mainAxis().getMaxScroll();
1605                if (mScrollOffsetPrimary + da > maxScroll) {
1606                    da = maxScroll - mScrollOffsetPrimary;
1607                }
1608            }
1609        } else if (da < 0) {
1610            if (!mWindowAlignment.mainAxis().isMinUnknown()) {
1611                int minScroll = mWindowAlignment.mainAxis().getMinScroll();
1612                if (mScrollOffsetPrimary + da < minScroll) {
1613                    da = minScroll - mScrollOffsetPrimary;
1614                }
1615            }
1616        }
1617        if (da == 0) {
1618            return 0;
1619        }
1620        offsetChildrenPrimary(-da);
1621        mScrollOffsetPrimary += da;
1622        if (mInLayout) {
1623            return da;
1624        }
1625
1626        int childCount = getChildCount();
1627        boolean updated;
1628
1629        if (da > 0) {
1630            appendVisibleItems();
1631        } else if (da < 0) {
1632            prependVisibleItems();
1633        }
1634        updated = getChildCount() > childCount;
1635        childCount = getChildCount();
1636
1637        if (da > 0) {
1638            removeInvisibleViewsAtFront();
1639        } else if (da < 0) {
1640            removeInvisibleViewsAtEnd();
1641        }
1642        updated |= getChildCount() < childCount;
1643
1644        if (updated) {
1645            updateRowSecondarySizeRefresh();
1646        }
1647
1648        mBaseGridView.invalidate();
1649        return da;
1650    }
1651
1652    // scroll in second direction will not add/prune views
1653    private int scrollDirectionSecondary(int dy) {
1654        if (dy == 0) {
1655            return 0;
1656        }
1657        offsetChildrenSecondary(-dy);
1658        mScrollOffsetSecondary += dy;
1659        mBaseGridView.invalidate();
1660        return dy;
1661    }
1662
1663    private void updateScrollMax() {
1664        if (mLastVisiblePos < 0) {
1665            return;
1666        }
1667        final boolean lastAvailable = mLastVisiblePos == mState.getItemCount() - 1;
1668        final boolean maxUnknown = mWindowAlignment.mainAxis().isMaxUnknown();
1669        if (!lastAvailable && maxUnknown) {
1670            return;
1671        }
1672        int maxEdge = Integer.MIN_VALUE;
1673        int rowIndex = -1;
1674        for (int i = 0; i < mRows.length; i++) {
1675            if (mRows[i].high > maxEdge) {
1676                maxEdge = mRows[i].high;
1677                rowIndex = i;
1678            }
1679        }
1680        int maxScroll = Integer.MAX_VALUE;
1681        for (int i = mLastVisiblePos; i >= mFirstVisiblePos; i--) {
1682            StaggeredGrid.Location location = mGrid.getLocation(i);
1683            if (location != null && location.row == rowIndex) {
1684                int savedMaxEdge = mWindowAlignment.mainAxis().getMaxEdge();
1685                mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1686                maxScroll = getPrimarySystemScrollPosition(findViewByPosition(i));
1687                mWindowAlignment.mainAxis().setMaxEdge(savedMaxEdge);
1688                break;
1689            }
1690        }
1691        if (lastAvailable) {
1692            mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1693            mWindowAlignment.mainAxis().setMaxScroll(maxScroll);
1694            if (DEBUG) Log.v(getTag(), "updating scroll maxEdge to " + maxEdge +
1695                    " scrollMax to " + maxScroll);
1696        } else {
1697            // the maxScroll for currently last visible item is larger,
1698            // so we must invalidate the max scroll value.
1699            if (maxScroll > mWindowAlignment.mainAxis().getMaxScroll()) {
1700                mWindowAlignment.mainAxis().invalidateScrollMax();
1701                if (DEBUG) Log.v(getTag(), "Invalidate scrollMax since it should be "
1702                        + "greater than " + maxScroll);
1703            }
1704        }
1705    }
1706
1707    private void updateScrollMin() {
1708        if (mFirstVisiblePos < 0) {
1709            return;
1710        }
1711        final boolean firstAvailable = mFirstVisiblePos == 0;
1712        final boolean minUnknown = mWindowAlignment.mainAxis().isMinUnknown();
1713        if (!firstAvailable && minUnknown) {
1714            return;
1715        }
1716        int minEdge = Integer.MAX_VALUE;
1717        int rowIndex = -1;
1718        for (int i = 0; i < mRows.length; i++) {
1719            if (mRows[i].low < minEdge) {
1720                minEdge = mRows[i].low;
1721                rowIndex = i;
1722            }
1723        }
1724        int minScroll = Integer.MIN_VALUE;
1725        for (int i = mFirstVisiblePos; i <= mLastVisiblePos; i++) {
1726            StaggeredGrid.Location location = mGrid.getLocation(i);
1727            if (location != null && location.row == rowIndex) {
1728                int savedMinEdge = mWindowAlignment.mainAxis().getMinEdge();
1729                mWindowAlignment.mainAxis().setMinEdge(minEdge);
1730                minScroll = getPrimarySystemScrollPosition(findViewByPosition(i));
1731                mWindowAlignment.mainAxis().setMinEdge(savedMinEdge);
1732                break;
1733            }
1734        }
1735        if (firstAvailable) {
1736            mWindowAlignment.mainAxis().setMinEdge(minEdge);
1737            mWindowAlignment.mainAxis().setMinScroll(minScroll);
1738            if (DEBUG) Log.v(getTag(), "updating scroll minEdge to " + minEdge +
1739                    " scrollMin to " + minScroll);
1740        } else {
1741            // the minScroll for currently first visible item is smaller,
1742            // so we must invalidate the min scroll value.
1743            if (minScroll < mWindowAlignment.mainAxis().getMinScroll()) {
1744                mWindowAlignment.mainAxis().invalidateScrollMin();
1745                if (DEBUG) Log.v(getTag(), "Invalidate scrollMin, since it should be "
1746                        + "less than " + minScroll);
1747            }
1748        }
1749    }
1750
1751    private void updateScrollSecondAxis() {
1752        mWindowAlignment.secondAxis().setMinEdge(0);
1753        mWindowAlignment.secondAxis().setMaxEdge(getSizeSecondary());
1754    }
1755
1756    private void initScrollController() {
1757        mWindowAlignment.horizontal.setSize(getWidth());
1758        mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight());
1759        mWindowAlignment.vertical.setSize(getHeight());
1760        mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom());
1761        mSizePrimary = mWindowAlignment.mainAxis().getSize();
1762
1763        if (DEBUG) {
1764            Log.v(getTag(), "initScrollController mSizePrimary " + mSizePrimary
1765                    + " mWindowAlignment " + mWindowAlignment);
1766        }
1767    }
1768
1769    public void setSelection(RecyclerView parent, int position) {
1770        setSelection(parent, position, false);
1771    }
1772
1773    public void setSelectionSmooth(RecyclerView parent, int position) {
1774        setSelection(parent, position, true);
1775    }
1776
1777    public int getSelection() {
1778        return mFocusPosition;
1779    }
1780
1781    public void setSelection(RecyclerView parent, int position, boolean smooth) {
1782        if (mFocusPosition == position) {
1783            return;
1784        }
1785        View view = findViewByPosition(position);
1786        if (view != null) {
1787            scrollToView(view, smooth);
1788        } else {
1789            mFocusPosition = position;
1790            if (!mLayoutEnabled) {
1791                return;
1792            }
1793            if (smooth) {
1794                if (!hasDoneFirstLayout()) {
1795                    Log.w(getTag(), "setSelectionSmooth should " +
1796                            "not be called before first layout pass");
1797                    return;
1798                }
1799                LinearSmoothScroller linearSmoothScroller =
1800                        new LinearSmoothScroller(parent.getContext()) {
1801                    @Override
1802                    public PointF computeScrollVectorForPosition(int targetPosition) {
1803                        if (getChildCount() == 0) {
1804                            return null;
1805                        }
1806                        final int firstChildPos = getPosition(getChildAt(0));
1807                        final int direction = targetPosition < firstChildPos ? -1 : 1;
1808                        if (mOrientation == HORIZONTAL) {
1809                            return new PointF(direction, 0);
1810                        } else {
1811                            return new PointF(0, direction);
1812                        }
1813                    }
1814                    @Override
1815                    protected void onTargetFound(View targetView,
1816                            RecyclerView.State state, Action action) {
1817                        if (hasFocus()) {
1818                            targetView.requestFocus();
1819                        } else {
1820                            dispatchChildSelected();
1821                        }
1822                        if (getScrollPosition(targetView, mTempDeltas)) {
1823                            int dx, dy;
1824                            if (mOrientation == HORIZONTAL) {
1825                                dx = mTempDeltas[0];
1826                                dy = mTempDeltas[1];
1827                            } else {
1828                                dx = mTempDeltas[1];
1829                                dy = mTempDeltas[0];
1830                            }
1831                            final int distance = (int) Math.sqrt(dx * dx + dy * dy);
1832                            final int time = calculateTimeForDeceleration(distance);
1833                            action.update(dx, dy, time, mDecelerateInterpolator);
1834                        }
1835                    }
1836                };
1837                linearSmoothScroller.setTargetPosition(position);
1838                startSmoothScroll(linearSmoothScroller);
1839            } else {
1840                mForceFullLayout = true;
1841                parent.requestLayout();
1842            }
1843        }
1844    }
1845
1846    @Override
1847    public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
1848        boolean needsLayout = false;
1849        if (itemCount != 0) {
1850            if (mFirstVisiblePos < 0) {
1851                needsLayout = true;
1852            } else if (!(positionStart > mLastVisiblePos + 1 ||
1853                    positionStart + itemCount < mFirstVisiblePos - 1)) {
1854                needsLayout = true;
1855            }
1856        }
1857        if (needsLayout) {
1858            recyclerView.requestLayout();
1859        }
1860    }
1861
1862    @Override
1863    public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) {
1864        if (mFocusSearchDisabled) {
1865            return true;
1866        }
1867        if (!mInLayout) {
1868            scrollToView(child, true);
1869        }
1870        return true;
1871    }
1872
1873    @Override
1874    public boolean requestChildRectangleOnScreen(RecyclerView parent, View view, Rect rect,
1875            boolean immediate) {
1876        if (DEBUG) Log.v(getTag(), "requestChildRectangleOnScreen " + view + " " + rect);
1877        return false;
1878    }
1879
1880    int getScrollOffsetX() {
1881        return mOrientation == HORIZONTAL ? mScrollOffsetPrimary : mScrollOffsetSecondary;
1882    }
1883
1884    int getScrollOffsetY() {
1885        return mOrientation == HORIZONTAL ? mScrollOffsetSecondary : mScrollOffsetPrimary;
1886    }
1887
1888    public void getViewSelectedOffsets(View view, int[] offsets) {
1889        if (mOrientation == HORIZONTAL) {
1890            offsets[0] = getPrimarySystemScrollPosition(view) - mScrollOffsetPrimary;
1891            offsets[1] = getSecondarySystemScrollPosition(view) - mScrollOffsetSecondary;
1892        } else {
1893            offsets[1] = getPrimarySystemScrollPosition(view) - mScrollOffsetPrimary;
1894            offsets[0] = getSecondarySystemScrollPosition(view) - mScrollOffsetSecondary;
1895        }
1896    }
1897
1898    private int getPrimarySystemScrollPosition(View view) {
1899        int viewCenterPrimary = mScrollOffsetPrimary + getViewCenter(view);
1900        int pos = getPositionByView(view);
1901        StaggeredGrid.Location location = mGrid.getLocation(pos);
1902        final int row = location.row;
1903        boolean isFirst = mFirstVisiblePos == 0;
1904        // TODO: change to use State object in onRequestChildFocus()
1905        boolean isLast = mLastVisiblePos == (mState == null ?
1906                getItemCount() : mState.getItemCount()) - 1;
1907        if (isFirst || isLast) {
1908            for (int i = getChildCount() - 1; i >= 0; i--) {
1909                int position = getPositionByIndex(i);
1910                StaggeredGrid.Location loc = mGrid.getLocation(position);
1911                if (loc != null && loc.row == row) {
1912                    if (position < pos) {
1913                        isFirst = false;
1914                    } else if (position > pos) {
1915                        isLast = false;
1916                    }
1917                }
1918            }
1919        }
1920        return mWindowAlignment.mainAxis().getSystemScrollPos(viewCenterPrimary, isFirst, isLast);
1921    }
1922
1923    private int getSecondarySystemScrollPosition(View view) {
1924        int viewCenterSecondary = mScrollOffsetSecondary + getViewCenterSecondary(view);
1925        int pos = getPositionByView(view);
1926        StaggeredGrid.Location location = mGrid.getLocation(pos);
1927        final int row = location.row;
1928        boolean isFirst = row == 0;
1929        boolean isLast = row == mGrid.getNumRows() - 1;
1930        return mWindowAlignment.secondAxis().getSystemScrollPos(viewCenterSecondary,
1931                isFirst, isLast);
1932    }
1933
1934    /**
1935     * Scroll to a given child view and change mFocusPosition.
1936     */
1937    private void scrollToView(View view, boolean smooth) {
1938        int newFocusPosition = getPositionByView(view);
1939        if (newFocusPosition != mFocusPosition) {
1940            mFocusPosition = newFocusPosition;
1941            if (!mInLayout) {
1942                dispatchChildSelected();
1943            }
1944        }
1945        if (mBaseGridView.isChildrenDrawingOrderEnabledInternal()) {
1946            mBaseGridView.invalidate();
1947        }
1948        if (view == null) {
1949            return;
1950        }
1951        if (!view.hasFocus() && mBaseGridView.hasFocus()) {
1952            // transfer focus to the child if it does not have focus yet (e.g. triggered
1953            // by setSelection())
1954            view.requestFocus();
1955        }
1956        if (getScrollPosition(view, mTempDeltas)) {
1957            scrollGrid(mTempDeltas[0], mTempDeltas[1], smooth);
1958        }
1959    }
1960
1961    private boolean getScrollPosition(View view, int[] deltas) {
1962        switch (mFocusScrollStrategy) {
1963        case BaseGridView.FOCUS_SCROLL_ALIGNED:
1964        default:
1965            return getAlignedPosition(view, deltas);
1966        case BaseGridView.FOCUS_SCROLL_ITEM:
1967        case BaseGridView.FOCUS_SCROLL_PAGE:
1968            return getNoneAlignedPosition(view, deltas);
1969        }
1970    }
1971
1972    private boolean getNoneAlignedPosition(View view, int[] deltas) {
1973        int pos = getPositionByView(view);
1974        int viewMin = getViewMin(view);
1975        int viewMax = getViewMax(view);
1976        // we either align "firstView" to left/top padding edge
1977        // or align "lastView" to right/bottom padding edge
1978        View firstView = null;
1979        View lastView = null;
1980        int paddingLow = mWindowAlignment.mainAxis().getPaddingLow();
1981        int clientSize = mWindowAlignment.mainAxis().getClientSize();
1982        final int row = mGrid.getLocation(pos).row;
1983        if (viewMin < paddingLow) {
1984            // view enters low padding area:
1985            firstView = view;
1986            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
1987                // scroll one "page" left/top,
1988                // align first visible item of the "page" at the low padding edge.
1989                while (!prependOneVisibleItem()) {
1990                    List<Integer> positions =
1991                            mGrid.getItemPositionsInRows(mFirstVisiblePos, pos)[row];
1992                    firstView = findViewByPosition(positions.get(0));
1993                    if (viewMax - getViewMin(firstView) > clientSize) {
1994                        if (positions.size() > 1) {
1995                            firstView = findViewByPosition(positions.get(1));
1996                        }
1997                        break;
1998                    }
1999                }
2000            }
2001        } else if (viewMax > clientSize + paddingLow) {
2002            // view enters high padding area:
2003            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
2004                // scroll whole one page right/bottom, align view at the low padding edge.
2005                firstView = view;
2006                do {
2007                    List<Integer> positions =
2008                            mGrid.getItemPositionsInRows(pos, mLastVisiblePos)[row];
2009                    lastView = findViewByPosition(positions.get(positions.size() - 1));
2010                    if (getViewMax(lastView) - viewMin > clientSize) {
2011                        lastView = null;
2012                        break;
2013                    }
2014                } while (!appendOneVisibleItem());
2015                if (lastView != null) {
2016                    // however if we reached end,  we should align last view.
2017                    firstView = null;
2018                }
2019            } else {
2020                lastView = view;
2021            }
2022        }
2023        int scrollPrimary = 0;
2024        int scrollSecondary = 0;
2025        if (firstView != null) {
2026            scrollPrimary = getViewMin(firstView) - paddingLow;
2027        } else if (lastView != null) {
2028            scrollPrimary = getViewMax(lastView) - (paddingLow + clientSize);
2029        }
2030        View secondaryAlignedView;
2031        if (firstView != null) {
2032            secondaryAlignedView = firstView;
2033        } else if (lastView != null) {
2034            secondaryAlignedView = lastView;
2035        } else {
2036            secondaryAlignedView = view;
2037        }
2038        scrollSecondary = getSecondarySystemScrollPosition(secondaryAlignedView);
2039        scrollSecondary -= mScrollOffsetSecondary;
2040        if (scrollPrimary != 0 || scrollSecondary != 0) {
2041            deltas[0] = scrollPrimary;
2042            deltas[1] = scrollSecondary;
2043            return true;
2044        }
2045        return false;
2046    }
2047
2048    private boolean getAlignedPosition(View view, int[] deltas) {
2049        int scrollPrimary = getPrimarySystemScrollPosition(view);
2050        int scrollSecondary = getSecondarySystemScrollPosition(view);
2051        if (DEBUG) {
2052            Log.v(getTag(), "getAlignedPosition " + scrollPrimary + " " + scrollSecondary
2053                    +" " + mWindowAlignment);
2054        }
2055        scrollPrimary -= mScrollOffsetPrimary;
2056        scrollSecondary -= mScrollOffsetSecondary;
2057        if (scrollPrimary != 0 || scrollSecondary != 0) {
2058            deltas[0] = scrollPrimary;
2059            deltas[1] = scrollSecondary;
2060            return true;
2061        }
2062        return false;
2063    }
2064
2065    private void scrollGrid(int scrollPrimary, int scrollSecondary, boolean smooth) {
2066        if (mInLayout) {
2067            scrollDirectionPrimary(scrollPrimary);
2068            scrollDirectionSecondary(scrollSecondary);
2069        } else {
2070            int scrollX;
2071            int scrollY;
2072            if (mOrientation == HORIZONTAL) {
2073                scrollX = scrollPrimary;
2074                scrollY = scrollSecondary;
2075            } else {
2076                scrollX = scrollSecondary;
2077                scrollY = scrollPrimary;
2078            }
2079            if (smooth) {
2080                mBaseGridView.smoothScrollBy(scrollX, scrollY);
2081            } else {
2082                mBaseGridView.scrollBy(scrollX, scrollY);
2083            }
2084        }
2085    }
2086
2087    public void setPruneChild(boolean pruneChild) {
2088        if (mPruneChild != pruneChild) {
2089            mPruneChild = pruneChild;
2090            if (mPruneChild) {
2091                requestLayout();
2092            }
2093        }
2094    }
2095
2096    public boolean getPruneChild() {
2097        return mPruneChild;
2098    }
2099
2100    private int findImmediateChildIndex(View view) {
2101        while (view != null && view != mBaseGridView) {
2102            int index = mBaseGridView.indexOfChild(view);
2103            if (index >= 0) {
2104                return index;
2105            }
2106            view = (View) view.getParent();
2107        }
2108        return NO_POSITION;
2109    }
2110
2111    void setFocusSearchDisabled(boolean disabled) {
2112        mFocusSearchDisabled = disabled;
2113    }
2114
2115    boolean isFocusSearchDisabled() {
2116        return mFocusSearchDisabled;
2117    }
2118
2119    @Override
2120    public View onInterceptFocusSearch(View focused, int direction) {
2121        if (mFocusSearchDisabled) {
2122            return focused;
2123        }
2124        return null;
2125    }
2126
2127    boolean hasPreviousViewInSameRow(int pos) {
2128        if (mGrid == null || pos == NO_POSITION) {
2129            return false;
2130        }
2131        if (mFirstVisiblePos > 0) {
2132            return true;
2133        }
2134        final int focusedRow = mGrid.getLocation(pos).row;
2135        for (int i = getChildCount() - 1; i >= 0; i--) {
2136            int position = getPositionByIndex(i);
2137            StaggeredGrid.Location loc = mGrid.getLocation(position);
2138            if (loc != null && loc.row == focusedRow) {
2139                if (position < pos) {
2140                    return true;
2141                }
2142            }
2143        }
2144        return false;
2145    }
2146
2147    @Override
2148    public boolean onAddFocusables(RecyclerView recyclerView,
2149            ArrayList<View> views, int direction, int focusableMode) {
2150        if (mFocusSearchDisabled) {
2151            return true;
2152        }
2153        // If this viewgroup or one of its children currently has focus then we
2154        // consider our children for focus searching in main direction on the same row.
2155        // If this viewgroup has no focus and using focus align, we want the system
2156        // to ignore our children and pass focus to the viewgroup, which will pass
2157        // focus on to its children appropriately.
2158        // If this viewgroup has no focus and not using focus align, we want to
2159        // consider the child that does not overlap with padding area.
2160        if (recyclerView.hasFocus()) {
2161            final int movement = getMovement(direction);
2162            if (movement != PREV_ITEM && movement != NEXT_ITEM) {
2163                // Move on secondary direction uses default addFocusables().
2164                return false;
2165            }
2166            final View focused = recyclerView.findFocus();
2167            final int focusedPos = getPositionByIndex(findImmediateChildIndex(focused));
2168            // Add focusables of focused item.
2169            if (focusedPos != NO_POSITION) {
2170                findViewByPosition(focusedPos).addFocusables(views,  direction, focusableMode);
2171            }
2172            final int focusedRow = mGrid != null && focusedPos != NO_POSITION ?
2173                    mGrid.getLocation(focusedPos).row : NO_POSITION;
2174            // Add focusables of next neighbor of same row on the focus search direction.
2175            if (mGrid != null) {
2176                final int focusableCount = views.size();
2177                for (int i = 0, count = getChildCount(); i < count; i++) {
2178                    int index = movement == NEXT_ITEM ? i : count - 1 - i;
2179                    final View child = getChildAt(index);
2180                    if (child.getVisibility() != View.VISIBLE) {
2181                        continue;
2182                    }
2183                    int position = getPositionByIndex(index);
2184                    StaggeredGrid.Location loc = mGrid.getLocation(position);
2185                    if (focusedRow == NO_POSITION || (loc != null && loc.row == focusedRow)) {
2186                        if (focusedPos == NO_POSITION ||
2187                                (movement == NEXT_ITEM && position > focusedPos)
2188                                || (movement == PREV_ITEM && position < focusedPos)) {
2189                            child.addFocusables(views,  direction, focusableMode);
2190                            if (views.size() > focusableCount) {
2191                                break;
2192                            }
2193                        }
2194                    }
2195                }
2196            }
2197        } else {
2198            if (mFocusScrollStrategy != BaseGridView.FOCUS_SCROLL_ALIGNED) {
2199                // adding views not overlapping padding area to avoid scrolling in gaining focus
2200                int left = mWindowAlignment.mainAxis().getPaddingLow();
2201                int right = mWindowAlignment.mainAxis().getClientSize() + left;
2202                int focusableCount = views.size();
2203                for (int i = 0, count = getChildCount(); i < count; i++) {
2204                    View child = getChildAt(i);
2205                    if (child.getVisibility() == View.VISIBLE) {
2206                        if (getViewMin(child) >= left && getViewMax(child) <= right) {
2207                            child.addFocusables(views, direction, focusableMode);
2208                        }
2209                    }
2210                }
2211                // if we cannot find any, then just add all children.
2212                if (views.size() == focusableCount) {
2213                    for (int i = 0, count = getChildCount(); i < count; i++) {
2214                        View child = getChildAt(i);
2215                        if (child.getVisibility() == View.VISIBLE) {
2216                            child.addFocusables(views, direction, focusableMode);
2217                        }
2218                    }
2219                    if (views.size() != focusableCount) {
2220                        return true;
2221                    }
2222                } else {
2223                    return true;
2224                }
2225                // if still cannot find any, fall through and add itself
2226            }
2227            if (recyclerView.isFocusable()) {
2228                views.add(recyclerView);
2229            }
2230        }
2231        return true;
2232    }
2233
2234    @Override
2235    public View onFocusSearchFailed(View focused, int direction, Recycler recycler,
2236            RecyclerView.State state) {
2237        if (DEBUG) Log.v(getTag(), "onFocusSearchFailed direction " + direction);
2238
2239        saveContext(recycler, state);
2240        View view = null;
2241        int movement = getMovement(direction);
2242        final FocusFinder ff = FocusFinder.getInstance();
2243        if (movement == NEXT_ITEM) {
2244            while (view == null && !appendOneVisibleItem()) {
2245                view = ff.findNextFocus(mBaseGridView, focused, direction);
2246            }
2247        } else if (movement == PREV_ITEM){
2248            while (view == null && !prependOneVisibleItem()) {
2249                view = ff.findNextFocus(mBaseGridView, focused, direction);
2250            }
2251        }
2252        if (view == null) {
2253            // returning the same view to prevent focus lost when scrolling past the end of the list
2254            if (movement == PREV_ITEM) {
2255                view = mFocusOutFront ? null : focused;
2256            } else if (movement == NEXT_ITEM){
2257                view = mFocusOutEnd ? null : focused;
2258            }
2259        }
2260        leaveContext();
2261        if (DEBUG) Log.v(getTag(), "returning view " + view);
2262        return view;
2263    }
2264
2265    boolean gridOnRequestFocusInDescendants(RecyclerView recyclerView, int direction,
2266            Rect previouslyFocusedRect) {
2267        switch (mFocusScrollStrategy) {
2268        case BaseGridView.FOCUS_SCROLL_ALIGNED:
2269        default:
2270            return gridOnRequestFocusInDescendantsAligned(recyclerView,
2271                    direction, previouslyFocusedRect);
2272        case BaseGridView.FOCUS_SCROLL_PAGE:
2273        case BaseGridView.FOCUS_SCROLL_ITEM:
2274            return gridOnRequestFocusInDescendantsUnaligned(recyclerView,
2275                    direction, previouslyFocusedRect);
2276        }
2277    }
2278
2279    private boolean gridOnRequestFocusInDescendantsAligned(RecyclerView recyclerView,
2280            int direction, Rect previouslyFocusedRect) {
2281        View view = findViewByPosition(mFocusPosition);
2282        if (view != null) {
2283            boolean result = view.requestFocus(direction, previouslyFocusedRect);
2284            if (!result && DEBUG) {
2285                Log.w(getTag(), "failed to request focus on " + view);
2286            }
2287            return result;
2288        }
2289        return false;
2290    }
2291
2292    private boolean gridOnRequestFocusInDescendantsUnaligned(RecyclerView recyclerView,
2293            int direction, Rect previouslyFocusedRect) {
2294        // focus to view not overlapping padding area to avoid scrolling in gaining focus
2295        int index;
2296        int increment;
2297        int end;
2298        int count = getChildCount();
2299        if ((direction & View.FOCUS_FORWARD) != 0) {
2300            index = 0;
2301            increment = 1;
2302            end = count;
2303        } else {
2304            index = count - 1;
2305            increment = -1;
2306            end = -1;
2307        }
2308        int left = mWindowAlignment.mainAxis().getPaddingLow();
2309        int right = mWindowAlignment.mainAxis().getClientSize() + left;
2310        for (int i = index; i != end; i += increment) {
2311            View child = getChildAt(i);
2312            if (child.getVisibility() == View.VISIBLE) {
2313                if (getViewMin(child) >= left && getViewMax(child) <= right) {
2314                    if (child.requestFocus(direction, previouslyFocusedRect)) {
2315                        return true;
2316                    }
2317                }
2318            }
2319        }
2320        return false;
2321    }
2322
2323    private final static int PREV_ITEM = 0;
2324    private final static int NEXT_ITEM = 1;
2325    private final static int PREV_ROW = 2;
2326    private final static int NEXT_ROW = 3;
2327
2328    private int getMovement(int direction) {
2329        int movement = View.FOCUS_LEFT;
2330
2331        if (mOrientation == HORIZONTAL) {
2332            switch(direction) {
2333                case View.FOCUS_LEFT:
2334                    movement = PREV_ITEM;
2335                    break;
2336                case View.FOCUS_RIGHT:
2337                    movement = NEXT_ITEM;
2338                    break;
2339                case View.FOCUS_UP:
2340                    movement = PREV_ROW;
2341                    break;
2342                case View.FOCUS_DOWN:
2343                    movement = NEXT_ROW;
2344                    break;
2345            }
2346         } else if (mOrientation == VERTICAL) {
2347             switch(direction) {
2348                 case View.FOCUS_LEFT:
2349                     movement = PREV_ROW;
2350                     break;
2351                 case View.FOCUS_RIGHT:
2352                     movement = NEXT_ROW;
2353                     break;
2354                 case View.FOCUS_UP:
2355                     movement = PREV_ITEM;
2356                     break;
2357                 case View.FOCUS_DOWN:
2358                     movement = NEXT_ITEM;
2359                     break;
2360             }
2361         }
2362
2363        return movement;
2364    }
2365
2366    int getChildDrawingOrder(RecyclerView recyclerView, int childCount, int i) {
2367        View view = findViewByPosition(mFocusPosition);
2368        if (view == null) {
2369            return i;
2370        }
2371        int focusIndex = recyclerView.indexOfChild(view);
2372        // supposely 0 1 2 3 4 5 6 7 8 9, 4 is the center item
2373        // drawing order is 0 1 2 3 9 8 7 6 5 4
2374        if (i < focusIndex) {
2375            return i;
2376        } else if (i < childCount - 1) {
2377            return focusIndex + childCount - 1 - i;
2378        } else {
2379            return focusIndex;
2380        }
2381    }
2382
2383    @Override
2384    public void onAdapterChanged(RecyclerView.Adapter oldAdapter,
2385            RecyclerView.Adapter newAdapter) {
2386        discardLayoutInfo();
2387        mFocusPosition = NO_POSITION;
2388        super.onAdapterChanged(oldAdapter, newAdapter);
2389    }
2390
2391    private void discardLayoutInfo() {
2392        mGrid = null;
2393        mRows = null;
2394        mRowSizeSecondary = null;
2395        mFirstVisiblePos = -1;
2396        mLastVisiblePos = -1;
2397        mRowSecondarySizeRefresh = false;
2398    }
2399
2400    public void setLayoutEnabled(boolean layoutEnabled) {
2401        if (mLayoutEnabled != layoutEnabled) {
2402            mLayoutEnabled = layoutEnabled;
2403            requestLayout();
2404        }
2405    }
2406}
2407