GridLayoutManager.java revision e34cae48707e70442aca13e1b4ab55757292828d
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.Rect;
19import android.support.v7.widget.RecyclerView;
20import android.support.v7.widget.RecyclerView.Adapter;
21import android.support.v7.widget.RecyclerView.Recycler;
22import android.support.v7.widget.RecyclerView.State;
23
24import static android.support.v7.widget.RecyclerView.NO_ID;
25import static android.support.v7.widget.RecyclerView.NO_POSITION;
26import static android.support.v7.widget.RecyclerView.HORIZONTAL;
27import static android.support.v7.widget.RecyclerView.VERTICAL;
28
29import android.util.AttributeSet;
30import android.util.Log;
31import android.view.FocusFinder;
32import android.view.Gravity;
33import android.view.View;
34import android.view.ViewParent;
35import android.view.View.MeasureSpec;
36import android.view.ViewGroup.MarginLayoutParams;
37import android.view.ViewGroup;
38import android.view.animation.DecelerateInterpolator;
39import android.view.animation.Interpolator;
40
41import java.io.PrintWriter;
42import java.io.StringWriter;
43import java.util.ArrayList;
44import java.util.List;
45
46final class GridLayoutManager extends RecyclerView.LayoutManager {
47
48     /*
49      * LayoutParams for {@link HorizontalGridView} and {@link VerticalGridView}.
50      * The class currently does three internal jobs:
51      * - Saves optical bounds insets.
52      * - Caches focus align view center.
53      * - Manages child view layout animation.
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        // For animations
71        private TimeAnimator mAnimator;
72        private long mDuration;
73        private boolean mFirstAttached;
74        // current virtual view position (scrollOffset + left/top) in the GridLayoutManager
75        private int mViewX, mViewY;
76        // animation start value of translation x and y
77        private float mAnimationStartTranslationX, mAnimationStartTranslationY;
78
79        public LayoutParams(Context c, AttributeSet attrs) {
80            super(c, attrs);
81        }
82
83        public LayoutParams(int width, int height) {
84            super(width, height);
85        }
86
87        public LayoutParams(MarginLayoutParams source) {
88            super(source);
89        }
90
91        public LayoutParams(ViewGroup.LayoutParams source) {
92            super(source);
93        }
94
95        public LayoutParams(RecyclerView.LayoutParams source) {
96            super(source);
97        }
98
99        public LayoutParams(LayoutParams source) {
100            super(source);
101        }
102
103        void onViewAttached() {
104            endAnimate();
105            mFirstAttached = true;
106        }
107
108        void onViewDetached() {
109            endAnimate();
110        }
111
112        int getAlignX() {
113            return mAlignX;
114        }
115
116        int getAlignY() {
117            return mAlignY;
118        }
119
120        int getOpticalLeft(View view) {
121            return view.getLeft() + mLeftInset;
122        }
123
124        int getOpticalTop(View view) {
125            return view.getTop() + mTopInset;
126        }
127
128        int getOpticalRight(View view) {
129            return view.getRight() - mRighInset;
130        }
131
132        int getOpticalBottom(View view) {
133            return view.getBottom() - mBottomInset;
134        }
135
136        int getOpticalWidth(View view) {
137            return view.getWidth() - mLeftInset - mRighInset;
138        }
139
140        int getOpticalHeight(View view) {
141            return view.getHeight() - mTopInset - mBottomInset;
142        }
143
144        void setAlignX(int alignX) {
145            mAlignX = alignX;
146        }
147
148        void setAlignY(int alignY) {
149            mAlignY = alignY;
150        }
151
152        void setOpticalInsets(int leftInset, int topInset, int rightInset, int bottomInset) {
153            mLeftInset = leftInset;
154            mTopInset = topInset;
155            mRighInset = rightInset;
156            mBottomInset = bottomInset;
157        }
158
159        private TimeAnimator.TimeListener mTimeListener = new TimeAnimator.TimeListener() {
160            @Override
161            public void onTimeUpdate(TimeAnimator animation, long totalTime, long deltaTime) {
162                if (mView == null) {
163                    return;
164                }
165                if (totalTime >= mDuration) {
166                    endAnimate();
167                } else {
168                    float fraction = (float) (totalTime / (double)mDuration);
169                    float fractionToEnd = 1 - mAnimator
170                        .getInterpolator().getInterpolation(fraction);
171                    mView.setTranslationX(fractionToEnd * mAnimationStartTranslationX);
172                    mView.setTranslationY(fractionToEnd * mAnimationStartTranslationY);
173                    invalidateItemDecoration();
174                }
175            }
176        };
177
178        void startAnimate(GridLayoutManager layout, View view, long startDelay) {
179            if (mAnimator == null) {
180                mAnimator = new TimeAnimator();
181                mAnimator.setTimeListener(mTimeListener);
182            }
183            if (mFirstAttached) {
184                // first time record the initial location and return without animation
185                // TODO do we need initial animation?
186                mViewX = layout.getScrollOffsetX() + getOpticalLeft(view);
187                mViewY = layout.getScrollOffsetY() + getOpticalTop(view);
188                mFirstAttached = false;
189                return;
190            }
191            mView = view;
192            int newViewX = layout.getScrollOffsetX() + getOpticalLeft(mView);
193            int newViewY = layout.getScrollOffsetY() + getOpticalTop(mView);
194            if (newViewX != mViewX || newViewY != mViewY) {
195                mAnimator.cancel();
196                mAnimationStartTranslationX = mView.getTranslationX();
197                mAnimationStartTranslationY = mView.getTranslationY();
198                mAnimationStartTranslationX += mViewX - newViewX;
199                mAnimationStartTranslationY += mViewY - newViewY;
200                mDuration = layout.getChildLayoutAnimationDuration();
201                mAnimator.setDuration(mDuration);
202                mAnimator.setInterpolator(layout.getChildLayoutAnimationInterpolator());
203                mAnimator.setStartDelay(startDelay);
204                mAnimator.start();
205                mViewX = newViewX;
206                mViewY = newViewY;
207            }
208        }
209
210        void endAnimate() {
211            if (mAnimator != null) {
212                mAnimator.end();
213            }
214            if (mView != null) {
215                mView.setTranslationX(0);
216                mView.setTranslationY(0);
217                mView = null;
218            }
219        }
220
221        private void invalidateItemDecoration() {
222            ViewParent parent = mView.getParent();
223            if (parent instanceof RecyclerView) {
224                // TODO: we only need invalidate parent if it has ItemDecoration
225                ((RecyclerView) parent).invalidate();
226            }
227        }
228    }
229
230    private static final String TAG = "GridLayoutManager";
231    private static final boolean DEBUG = false;
232
233    private static final Interpolator sDefaultAnimationChildLayoutInterpolator
234            = new DecelerateInterpolator();
235
236    private static final long DEFAULT_CHILD_ANIMATION_DURATION_MS = 250;
237
238    private String getTag() {
239        return TAG + ":" + mBaseGridView.getId();
240    }
241
242    private final BaseGridView mBaseGridView;
243
244    /**
245     * The orientation of a "row".
246     */
247    private int mOrientation = HORIZONTAL;
248
249    private RecyclerView.Adapter mAdapter;
250    private RecyclerView.Recycler mRecycler;
251
252    private boolean mInLayout = false;
253
254    private OnChildSelectedListener mChildSelectedListener = null;
255
256    /**
257     * The focused position, it's not the currently visually aligned position
258     * but it is the final position that we intend to focus on. If there are
259     * multiple setSelection() called, mFocusPosition saves last value.
260     */
261    private int mFocusPosition = NO_POSITION;
262
263    /**
264     * Force a full layout under certain situations.
265     */
266    private boolean mForceFullLayout;
267
268    /**
269     * The scroll offsets of the viewport relative to the entire view.
270     */
271    private int mScrollOffsetPrimary;
272    private int mScrollOffsetSecondary;
273
274    /**
275     * User-specified row height/column width.  Can be WRAP_CONTENT.
276     */
277    private int mRowSizeSecondaryRequested;
278
279    /**
280     * The fixed size of each grid item in the secondary direction. This corresponds to
281     * the row height, equal for all rows. Grid items may have variable length
282     * in the primary direction.
283     */
284    private int mFixedRowSizeSecondary;
285
286    /**
287     * Tracks the secondary size of each row.
288     */
289    private int[] mRowSizeSecondary;
290
291    /**
292     * Flag controlling whether the current/next layout should
293     * be updating the secondary size of rows.
294     */
295    private boolean mRowSecondarySizeRefresh;
296
297    /**
298     * The maximum measured size of the view.
299     */
300    private int mMaxSizeSecondary;
301
302    /**
303     * Margin between items.
304     */
305    private int mHorizontalMargin;
306    /**
307     * Margin between items vertically.
308     */
309    private int mVerticalMargin;
310    /**
311     * Margin in main direction.
312     */
313    private int mMarginPrimary;
314    /**
315     * Margin in second direction.
316     */
317    private int mMarginSecondary;
318    /**
319     * How to position child in secondary direction.
320     */
321    private int mGravity = Gravity.LEFT | Gravity.TOP;
322    /**
323     * The number of rows in the grid.
324     */
325    private int mNumRows;
326    /**
327     * Number of rows requested, can be 0 to be determined by parent size and
328     * rowHeight.
329     */
330    private int mNumRowsRequested = 1;
331
332    /**
333     * Tracking start/end position of each row for visible items.
334     */
335    private StaggeredGrid.Row[] mRows;
336
337    /**
338     * Saves grid information of each view.
339     */
340    private StaggeredGrid mGrid;
341    /**
342     * Position of first item (included) that has attached views.
343     */
344    private int mFirstVisiblePos;
345    /**
346     * Position of last item (included) that has attached views.
347     */
348    private int mLastVisiblePos;
349
350    /**
351     * Focus Scroll strategy.
352     */
353    private int mFocusScrollStrategy = BaseGridView.FOCUS_SCROLL_ALIGNED;
354    /**
355     * Defines how item view is aligned in the window.
356     */
357    private final WindowAlignment mWindowAlignment = new WindowAlignment();
358
359    /**
360     * Defines how item view is aligned.
361     */
362    private final ItemAlignment mItemAlignment = new ItemAlignment();
363
364    /**
365     * Dimensions of the view, width or height depending on orientation.
366     */
367    private int mSizePrimary;
368
369    /**
370     *  Allow DPAD key to navigate out at the front of the View (where position = 0),
371     *  default is false.
372     */
373    private boolean mFocusOutFront;
374
375    /**
376     * Allow DPAD key to navigate out at the end of the view, default is false.
377     */
378    private boolean mFocusOutEnd;
379
380    /**
381     * True if focus search is disabled.
382     */
383    private boolean mFocusSearchDisabled;
384
385    /**
386     * Animate layout changes from a child resizing or adding/removing a child.
387     */
388    private boolean mAnimateChildLayout = true;
389
390    /**
391     * Interpolator used to animate layout of children.
392     */
393    private Interpolator mAnimateLayoutChildInterpolator = sDefaultAnimationChildLayoutInterpolator;
394
395    /**
396     * Duration used to animate layout of children.
397     */
398    private long mAnimateLayoutChildDuration = DEFAULT_CHILD_ANIMATION_DURATION_MS;
399
400    public GridLayoutManager(BaseGridView baseGridView) {
401        mBaseGridView = baseGridView;
402    }
403
404    public void setOrientation(int orientation) {
405        if (orientation != HORIZONTAL && orientation != VERTICAL) {
406            if (DEBUG) Log.v(getTag(), "invalid orientation: " + orientation);
407            return;
408        }
409
410        mOrientation = orientation;
411        mWindowAlignment.setOrientation(orientation);
412        mItemAlignment.setOrientation(orientation);
413        mForceFullLayout = true;
414    }
415
416    public int getFocusScrollStrategy() {
417        return mFocusScrollStrategy;
418    }
419
420    public void setFocusScrollStrategy(int focusScrollStrategy) {
421        mFocusScrollStrategy = focusScrollStrategy;
422    }
423
424    public void setWindowAlignment(int windowAlignment) {
425        mWindowAlignment.mainAxis().setWindowAlignment(windowAlignment);
426    }
427
428    public int getWindowAlignment() {
429        return mWindowAlignment.mainAxis().getWindowAlignment();
430    }
431
432    public void setWindowAlignmentOffset(int alignmentOffset) {
433        mWindowAlignment.mainAxis().setWindowAlignmentOffset(alignmentOffset);
434    }
435
436    public int getWindowAlignmentOffset() {
437        return mWindowAlignment.mainAxis().getWindowAlignmentOffset();
438    }
439
440    public void setWindowAlignmentOffsetPercent(float offsetPercent) {
441        mWindowAlignment.mainAxis().setWindowAlignmentOffsetPercent(offsetPercent);
442    }
443
444    public float getWindowAlignmentOffsetPercent() {
445        return mWindowAlignment.mainAxis().getWindowAlignmentOffsetPercent();
446    }
447
448    public void setItemAlignmentOffset(int alignmentOffset) {
449        mItemAlignment.mainAxis().setItemAlignmentOffset(alignmentOffset);
450        updateChildAlignments();
451    }
452
453    public int getItemAlignmentOffset() {
454        return mItemAlignment.mainAxis().getItemAlignmentOffset();
455    }
456
457    public void setItemAlignmentOffsetPercent(float offsetPercent) {
458        mItemAlignment.mainAxis().setItemAlignmentOffsetPercent(offsetPercent);
459        updateChildAlignments();
460    }
461
462    public float getItemAlignmentOffsetPercent() {
463        return mItemAlignment.mainAxis().getItemAlignmentOffsetPercent();
464    }
465
466    public void setItemAlignmentViewId(int viewId) {
467        mItemAlignment.mainAxis().setItemAlignmentViewId(viewId);
468        updateChildAlignments();
469    }
470
471    public int getItemAlignmentViewId() {
472        return mItemAlignment.mainAxis().getItemAlignmentViewId();
473    }
474
475    public void setFocusOutAllowed(boolean throughFront, boolean throughEnd) {
476        mFocusOutFront = throughFront;
477        mFocusOutEnd = throughEnd;
478    }
479
480    public void setNumRows(int numRows) {
481        if (numRows < 0) throw new IllegalArgumentException();
482        mNumRowsRequested = numRows;
483        mForceFullLayout = true;
484    }
485
486    /**
487     * Set the row height. May be WRAP_CONTENT, or a size in pixels.
488     */
489    public void setRowHeight(int height) {
490        if (height >= 0 || height == ViewGroup.LayoutParams.WRAP_CONTENT) {
491            mRowSizeSecondaryRequested = height;
492        } else {
493            throw new IllegalArgumentException("Invalid row height: " + height);
494        }
495    }
496
497    public void setItemMargin(int margin) {
498        mVerticalMargin = mHorizontalMargin = margin;
499        mMarginPrimary = mMarginSecondary = margin;
500    }
501
502    public void setVerticalMargin(int margin) {
503        if (mOrientation == HORIZONTAL) {
504            mMarginSecondary = mVerticalMargin = margin;
505        } else {
506            mMarginPrimary = mVerticalMargin = margin;
507        }
508    }
509
510    public void setHorizontalMargin(int margin) {
511        if (mOrientation == HORIZONTAL) {
512            mMarginPrimary = mHorizontalMargin = margin;
513        } else {
514            mMarginSecondary = mHorizontalMargin = margin;
515        }
516    }
517
518    public int getVerticalMargin() {
519        return mVerticalMargin;
520    }
521
522    public int getHorizontalMargin() {
523        return mHorizontalMargin;
524    }
525
526    public void setGravity(int gravity) {
527        mGravity = gravity;
528    }
529
530    protected boolean hasDoneFirstLayout() {
531        return mGrid != null;
532    }
533
534    public void setOnChildSelectedListener(OnChildSelectedListener listener) {
535        mChildSelectedListener = listener;
536    }
537
538    private int getPositionByView(View view) {
539        return getPositionByIndex(mBaseGridView.indexOfChild(view));
540    }
541
542    private int getPositionByIndex(int index) {
543        if (index < 0) {
544            return NO_POSITION;
545        }
546        return mFirstVisiblePos + index;
547    }
548
549    private View getViewByPosition(int position) {
550        int index = getIndexByPosition(position);
551        if (index < 0) {
552            return null;
553        }
554        return getChildAt(index);
555    }
556
557    private int getIndexByPosition(int position) {
558        if (mFirstVisiblePos < 0 ||
559                position < mFirstVisiblePos || position > mLastVisiblePos) {
560            return NO_POSITION;
561        }
562        return position - mFirstVisiblePos;
563    }
564
565    private void dispatchChildSelected() {
566        if (mChildSelectedListener == null) {
567            return;
568        }
569
570        View view = getViewByPosition(mFocusPosition);
571
572        if (mFocusPosition != NO_POSITION) {
573            mChildSelectedListener.onChildSelected(mBaseGridView, view, mFocusPosition,
574                    mAdapter.getItemId(mFocusPosition));
575        } else {
576            mChildSelectedListener.onChildSelected(mBaseGridView, null, NO_POSITION, NO_ID);
577        }
578    }
579
580    @Override
581    public boolean canScrollHorizontally() {
582        // We can scroll horizontally if we have horizontal orientation, or if
583        // we are vertical and have more than one column.
584        return mOrientation == HORIZONTAL || mNumRows > 1;
585    }
586
587    @Override
588    public boolean canScrollVertically() {
589        // We can scroll vertically if we have vertical orientation, or if we
590        // are horizontal and have more than one row.
591        return mOrientation == VERTICAL || mNumRows > 1;
592    }
593
594    @Override
595    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
596        return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
597                ViewGroup.LayoutParams.WRAP_CONTENT);
598    }
599
600    @Override
601    public RecyclerView.LayoutParams generateLayoutParams(Context context, AttributeSet attrs) {
602        return new LayoutParams(context, attrs);
603    }
604
605    @Override
606    public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
607        if (lp instanceof LayoutParams) {
608            return new LayoutParams((LayoutParams) lp);
609        } else if (lp instanceof RecyclerView.LayoutParams) {
610            return new LayoutParams((RecyclerView.LayoutParams) lp);
611        } else if (lp instanceof MarginLayoutParams) {
612            return new LayoutParams((MarginLayoutParams) lp);
613        } else {
614            return new LayoutParams(lp);
615        }
616    }
617
618    protected View getViewForPosition(int position) {
619        View v = mRecycler.getViewForPosition(mAdapter, position);
620        if (v != null) {
621            ((LayoutParams) v.getLayoutParams()).onViewAttached();
622        }
623        return v;
624    }
625
626    final int getOpticalLeft(View v) {
627        return ((LayoutParams) v.getLayoutParams()).getOpticalLeft(v);
628    }
629
630    final int getOpticalRight(View v) {
631        return ((LayoutParams) v.getLayoutParams()).getOpticalRight(v);
632    }
633
634    final int getOpticalTop(View v) {
635        return ((LayoutParams) v.getLayoutParams()).getOpticalTop(v);
636    }
637
638    final int getOpticalBottom(View v) {
639        return ((LayoutParams) v.getLayoutParams()).getOpticalBottom(v);
640    }
641
642    private int getViewMin(View v) {
643        return (mOrientation == HORIZONTAL) ? getOpticalLeft(v) : getOpticalTop(v);
644    }
645
646    private int getViewMax(View v) {
647        return (mOrientation == HORIZONTAL) ? getOpticalRight(v) : getOpticalBottom(v);
648    }
649
650    private int getViewCenter(View view) {
651        return (mOrientation == HORIZONTAL) ? getViewCenterX(view) : getViewCenterY(view);
652    }
653
654    private int getViewCenterSecondary(View view) {
655        return (mOrientation == HORIZONTAL) ? getViewCenterY(view) : getViewCenterX(view);
656    }
657
658    private int getViewCenterX(View v) {
659        LayoutParams p = (LayoutParams) v.getLayoutParams();
660        return p.getOpticalLeft(v) + p.getAlignX();
661    }
662
663    private int getViewCenterY(View v) {
664        LayoutParams p = (LayoutParams) v.getLayoutParams();
665        return p.getOpticalTop(v) + p.getAlignY();
666    }
667
668    /**
669     * Re-initialize data structures for a data change or handling invisible
670     * selection. The method tries its best to preserve position information so
671     * that staggered grid looks same before and after re-initialize.
672     * @param focusPosition The initial focusPosition that we would like to
673     *        focus on.
674     * @return Actual position that can be focused on.
675     */
676    private int init(RecyclerView.Adapter adapter, RecyclerView.Recycler recycler,
677            int focusPosition) {
678
679        final int newItemCount = adapter.getItemCount();
680
681        if (focusPosition == NO_POSITION && newItemCount > 0) {
682            // if focus position is never set before,  initialize it to 0
683            focusPosition = 0;
684        }
685        // If adapter has changed then caches are invalid; otherwise,
686        // we try to maintain each row's position if number of rows keeps the same
687        // and existing mGrid contains the focusPosition.
688        if (mRows != null && mNumRows == mRows.length &&
689                mGrid != null && mGrid.getSize() > 0 && focusPosition >= 0 &&
690                focusPosition >= mGrid.getFirstIndex() &&
691                focusPosition <= mGrid.getLastIndex()) {
692            // strip mGrid to a subset (like a column) that contains focusPosition
693            mGrid.stripDownTo(focusPosition);
694            // make sure that remaining items do not exceed new adapter size
695            int firstIndex = mGrid.getFirstIndex();
696            int lastIndex = mGrid.getLastIndex();
697            if (DEBUG) {
698                Log .v(getTag(), "mGrid firstIndex " + firstIndex + " lastIndex " + lastIndex);
699            }
700            for (int i = lastIndex; i >=firstIndex; i--) {
701                if (i >= newItemCount) {
702                    mGrid.removeLast();
703                }
704            }
705            if (mGrid.getSize() == 0) {
706                focusPosition = newItemCount - 1;
707                // initialize row start locations
708                for (int i = 0; i < mNumRows; i++) {
709                    mRows[i].low = 0;
710                    mRows[i].high = 0;
711                }
712                if (DEBUG) Log.v(getTag(), "mGrid zero size");
713            } else {
714                // initialize row start locations
715                for (int i = 0; i < mNumRows; i++) {
716                    mRows[i].low = Integer.MAX_VALUE;
717                    mRows[i].high = Integer.MIN_VALUE;
718                }
719                firstIndex = mGrid.getFirstIndex();
720                lastIndex = mGrid.getLastIndex();
721                if (focusPosition > lastIndex) {
722                    focusPosition = mGrid.getLastIndex();
723                }
724                if (DEBUG) {
725                    Log.v(getTag(), "mGrid firstIndex " + firstIndex + " lastIndex "
726                        + lastIndex + " focusPosition " + focusPosition);
727                }
728                // fill rows with minimal view positions of the subset
729                for (int i = firstIndex; i <= lastIndex; i++) {
730                    View v = getViewByPosition(i);
731                    if (v == null) {
732                        continue;
733                    }
734                    int row = mGrid.getLocation(i).row;
735                    int low = getViewMin(v) + mScrollOffsetPrimary;
736                    if (low < mRows[row].low) {
737                        mRows[row].low = mRows[row].high = low;
738                    }
739                }
740                // fill other rows that does not include the subset using first item
741                int firstItemRowPosition = mRows[mGrid.getLocation(firstIndex).row].low;
742                if (firstItemRowPosition == Integer.MAX_VALUE) {
743                    firstItemRowPosition = 0;
744                }
745                for (int i = 0; i < mNumRows; i++) {
746                    if (mRows[i].low == Integer.MAX_VALUE) {
747                        mRows[i].low = mRows[i].high = firstItemRowPosition;
748                    }
749                }
750            }
751
752            // Same adapter, we can reuse any attached views
753            detachAndScrapAttachedViews(recycler);
754
755        } else {
756            // otherwise recreate data structure
757            mRows = new StaggeredGrid.Row[mNumRows];
758            mRowSizeSecondary = new int[mNumRows];
759
760            for (int i = 0; i < mNumRows; i++) {
761                mRows[i] = new StaggeredGrid.Row();
762            }
763            mGrid = new StaggeredGridDefault();
764            if (newItemCount == 0) {
765                focusPosition = NO_POSITION;
766            } else if (focusPosition >= newItemCount) {
767                focusPosition = newItemCount - 1;
768            }
769
770            // Adapter may have changed so remove all attached views permanently
771            removeAllViews();
772
773            mScrollOffsetPrimary = 0;
774            mScrollOffsetSecondary = 0;
775            mWindowAlignment.reset();
776        }
777
778        mAdapter = adapter;
779        mRecycler = recycler;
780        mGrid.setProvider(mGridProvider);
781        // mGrid share the same Row array information
782        mGrid.setRows(mRows);
783        mFirstVisiblePos = mLastVisiblePos = NO_POSITION;
784
785        initScrollController();
786        updateScrollSecondAxis();
787
788        return focusPosition;
789    }
790
791    private int getRowSizeSecondary(int rowIndex) {
792        if (mFixedRowSizeSecondary != 0) {
793            return mFixedRowSizeSecondary;
794        }
795        if (mRowSizeSecondary == null) {
796            return 0;
797        }
798        return mRowSizeSecondary[rowIndex];
799    }
800
801    private int getRowStartSecondary(int rowIndex) {
802        int start = 0;
803        for (int i = 0; i < rowIndex; i++) {
804            start += getRowSizeSecondary(i) + mMarginSecondary;
805        }
806        return start;
807    }
808
809    private int getSizeSecondary() {
810        return getRowStartSecondary(mNumRows - 1) + getRowSizeSecondary(mNumRows - 1);
811    }
812
813    private boolean processRowSizeSecondary(boolean measure) {
814        if (mFixedRowSizeSecondary != 0) {
815            return false;
816        }
817
818        List<Integer>[] rows = mGrid.getItemPositionsInRows(mFirstVisiblePos, mLastVisiblePos);
819        boolean changed = false;
820
821        for (int rowIndex = 0; rowIndex < mNumRows; rowIndex++) {
822            int rowSize = 0;
823
824            final int rowItemCount = rows[rowIndex].size();
825            if (DEBUG) Log.v(getTag(), "processRowSizeSecondary row " + rowIndex +
826                    " rowItemCount " + rowItemCount);
827
828            for (int i = 0; i < rowItemCount; i++) {
829                final int position = rows[rowIndex].get(i);
830                final View view = getViewByPosition(position);
831                if (measure && view.isLayoutRequested()) {
832                    measureChild(view, rowIndex);
833                }
834                // If this view isn't visible, we ignore it.
835                if (getOpticalRight(view) < 0 || getOpticalLeft(view) > getWidth() ||
836                        getOpticalBottom(view) < 0 || getOpticalTop(view) > getHeight()) {
837                    continue;
838                }
839                final int secondarySize = mOrientation == HORIZONTAL ?
840                        view.getMeasuredHeight() : view.getMeasuredWidth();
841                if (secondarySize > rowSize) {
842                    rowSize = secondarySize;
843                }
844            }
845            if (DEBUG) Log.v(getTag(), "row " + rowIndex + " rowItemCount " + rowItemCount +
846                    " rowSize " + rowSize);
847
848            if (mRowSizeSecondary[rowIndex] != rowSize) {
849                if (DEBUG) Log.v(getTag(), "row size secondary changed: " + mRowSizeSecondary[rowIndex] +
850                        ", " + rowSize);
851
852                mRowSizeSecondary[rowIndex] = rowSize;
853                changed = true;
854            }
855        }
856
857        return changed;
858    }
859
860    /**
861     * Checks if we need to update row secondary sizes.
862     */
863    private void updateRowSecondarySizeRefresh() {
864        mRowSecondarySizeRefresh = processRowSizeSecondary(false);
865        if (mRowSecondarySizeRefresh) {
866            if (DEBUG) Log.v(getTag(), "mRowSecondarySizeRefresh now set");
867            forceRequestLayout();
868        }
869    }
870
871    private void forceRequestLayout() {
872        if (DEBUG) Log.v(getTag(), "forceRequestLayout");
873        // RecyclerView prevents us from requesting layout in many cases
874        // (during layout, during scroll, etc.)
875        // For secondary row size wrap_content support we currently need a
876        // second layout pass to update the measured size after having measured
877        // and added child views in layoutChildren.
878        // Force the second layout by posting a delayed runnable.
879        // TODO: investigate allowing a second layout pass,
880        // or move child add/measure logic to the measure phase.
881        mBaseGridView.getHandler().post(new Runnable() {
882           @Override
883           public void run() {
884               if (DEBUG) Log.v(getTag(), "request Layout from runnable");
885               requestLayout();
886           }
887        });
888    }
889
890    @Override
891    public void onMeasure(int widthSpec, int heightSpec) {
892        int sizePrimary, sizeSecondary, modeSecondary, paddingSecondary;
893        int measuredSizeSecondary;
894        if (mOrientation == HORIZONTAL) {
895            sizePrimary = MeasureSpec.getSize(widthSpec);
896            sizeSecondary = MeasureSpec.getSize(heightSpec);
897            modeSecondary = MeasureSpec.getMode(heightSpec);
898            paddingSecondary = getPaddingTop() + getPaddingBottom();
899        } else {
900            sizeSecondary = MeasureSpec.getSize(widthSpec);
901            sizePrimary = MeasureSpec.getSize(heightSpec);
902            modeSecondary = MeasureSpec.getMode(widthSpec);
903            paddingSecondary = getPaddingLeft() + getPaddingRight();
904        }
905        if (DEBUG) Log.v(getTag(), "onMeasure widthSpec " + Integer.toHexString(widthSpec) +
906                " heightSpec " + Integer.toHexString(heightSpec) +
907                " modeSecondary " + Integer.toHexString(modeSecondary) +
908                " sizeSecondary " + sizeSecondary + " " + this);
909
910        mMaxSizeSecondary = sizeSecondary;
911
912        if (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) {
913            mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested;
914            mFixedRowSizeSecondary = 0;
915
916            // Measure all current children and update cached row heights
917            if (mGrid != null) {
918                processRowSizeSecondary(true);
919            }
920
921            switch (modeSecondary) {
922            case MeasureSpec.UNSPECIFIED:
923                measuredSizeSecondary = getSizeSecondary() + paddingSecondary;
924                break;
925            case MeasureSpec.AT_MOST:
926                measuredSizeSecondary = Math.min(getSizeSecondary() + paddingSecondary,
927                        mMaxSizeSecondary);
928                break;
929            case MeasureSpec.EXACTLY:
930                measuredSizeSecondary = mMaxSizeSecondary;
931                break;
932            default:
933                throw new IllegalStateException("wrong spec");
934            }
935
936        } else {
937            switch (modeSecondary) {
938            case MeasureSpec.UNSPECIFIED:
939                if (mRowSizeSecondaryRequested == 0) {
940                    if (mOrientation == HORIZONTAL) {
941                        throw new IllegalStateException("Must specify rowHeight or view height");
942                    } else {
943                        throw new IllegalStateException("Must specify columnWidth or view width");
944                    }
945                }
946                mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
947                mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested;
948                measuredSizeSecondary = mFixedRowSizeSecondary * mNumRows + mMarginSecondary
949                    * (mNumRows - 1) + paddingSecondary;
950                break;
951            case MeasureSpec.AT_MOST:
952            case MeasureSpec.EXACTLY:
953                if (mNumRowsRequested == 0 && mRowSizeSecondaryRequested == 0) {
954                    mNumRows = 1;
955                    mFixedRowSizeSecondary = sizeSecondary - paddingSecondary;
956                } else if (mNumRowsRequested == 0) {
957                    mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
958                    mNumRows = (sizeSecondary + mMarginSecondary)
959                        / (mRowSizeSecondaryRequested + mMarginSecondary);
960                } else if (mRowSizeSecondaryRequested == 0) {
961                    mNumRows = mNumRowsRequested;
962                    mFixedRowSizeSecondary = (sizeSecondary - paddingSecondary - mMarginSecondary
963                            * (mNumRows - 1)) / mNumRows;
964                } else {
965                    mNumRows = mNumRowsRequested;
966                    mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
967                }
968                measuredSizeSecondary = sizeSecondary;
969                if (modeSecondary == MeasureSpec.AT_MOST) {
970                    int childrenSize = mFixedRowSizeSecondary * mNumRows + mMarginSecondary
971                        * (mNumRows - 1) + paddingSecondary;
972                    if (childrenSize < measuredSizeSecondary) {
973                        measuredSizeSecondary = childrenSize;
974                    }
975                }
976                break;
977            default:
978                throw new IllegalStateException("wrong spec");
979            }
980        }
981        if (mOrientation == HORIZONTAL) {
982            setMeasuredDimension(sizePrimary, measuredSizeSecondary);
983        } else {
984            setMeasuredDimension(measuredSizeSecondary, sizePrimary);
985        }
986        if (DEBUG) {
987            Log.v(getTag(), "onMeasure sizePrimary " + sizePrimary +
988                    " measuredSizeSecondary " + measuredSizeSecondary +
989                    " mFixedRowSizeSecondary " + mFixedRowSizeSecondary +
990                    " mNumRows " + mNumRows);
991        }
992    }
993
994    private void measureChild(View child, int rowIndex) {
995        final ViewGroup.LayoutParams lp = child.getLayoutParams();
996        final int secondarySpec = (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) ?
997                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) :
998                MeasureSpec.makeMeasureSpec(mFixedRowSizeSecondary, MeasureSpec.EXACTLY);
999        int widthSpec, heightSpec;
1000
1001        if (mOrientation == HORIZONTAL) {
1002            widthSpec = ViewGroup.getChildMeasureSpec(
1003                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
1004                    0, lp.width);
1005            heightSpec = ViewGroup.getChildMeasureSpec(secondarySpec, 0, lp.height);
1006        } else {
1007            heightSpec = ViewGroup.getChildMeasureSpec(
1008                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
1009                    0, lp.height);
1010            widthSpec = ViewGroup.getChildMeasureSpec(secondarySpec, 0, lp.width);
1011        }
1012
1013        child.measure(widthSpec, heightSpec);
1014
1015        if (DEBUG) Log.v(getTag(), "measureChild secondarySpec " + Integer.toHexString(secondarySpec) +
1016                " widthSpec " + Integer.toHexString(widthSpec) +
1017                " heightSpec " + Integer.toHexString(heightSpec) +
1018                " measuredWidth " + child.getMeasuredWidth() +
1019                " measuredHeight " + child.getMeasuredHeight());
1020        if (DEBUG) Log.v(getTag(), "child lp width " + lp.width + " height " + lp.height);
1021    }
1022
1023    private StaggeredGrid.Provider mGridProvider = new StaggeredGrid.Provider() {
1024
1025        @Override
1026        public int getCount() {
1027            return mAdapter.getItemCount();
1028        }
1029
1030        @Override
1031        public void createItem(int index, int rowIndex, boolean append) {
1032            View v = getViewForPosition(index);
1033            if (mFirstVisiblePos >= 0) {
1034                // when StaggeredGrid append or prepend item, we must guarantee
1035                // that sibling item has created views already.
1036                if (append && index != mLastVisiblePos + 1) {
1037                    throw new RuntimeException();
1038                } else if (!append && index != mFirstVisiblePos - 1) {
1039                    throw new RuntimeException();
1040                }
1041            }
1042
1043            if (append) {
1044                addView(v);
1045            } else {
1046                addView(v, 0);
1047            }
1048
1049            measureChild(v, rowIndex);
1050
1051            int length = mOrientation == HORIZONTAL ? v.getMeasuredWidth() : v.getMeasuredHeight();
1052            int start, end;
1053            if (append) {
1054                start = mRows[rowIndex].high;
1055                if (start != mRows[rowIndex].low) {
1056                    // if there are existing item in the row,  add margin between
1057                    start += mMarginPrimary;
1058                } else {
1059                    final int lastRow = mRows.length - 1;
1060                    if (lastRow != rowIndex && mRows[lastRow].high != mRows[lastRow].low) {
1061                        // if there are existing item in the last row, insert
1062                        // the new item after the last item of last row.
1063                        start = mRows[lastRow].high + mMarginPrimary;
1064                    }
1065                }
1066                end = start + length;
1067                mRows[rowIndex].high = end;
1068            } else {
1069                end = mRows[rowIndex].low;
1070                if (end != mRows[rowIndex].high) {
1071                    end -= mMarginPrimary;
1072                } else if (0 != rowIndex && mRows[0].high != mRows[0].low) {
1073                    // if there are existing item in the first row, insert
1074                    // the new item before the first item of first row.
1075                    end = mRows[0].low - mMarginPrimary;
1076                }
1077                start = end - length;
1078                mRows[rowIndex].low = start;
1079            }
1080            if (mFirstVisiblePos < 0) {
1081                mFirstVisiblePos = mLastVisiblePos = index;
1082            } else {
1083                if (append) {
1084                    mLastVisiblePos++;
1085                } else {
1086                    mFirstVisiblePos--;
1087                }
1088            }
1089            if (DEBUG) Log.v(getTag(), "start " + start + " end " + end);
1090            int startSecondary = getRowStartSecondary(rowIndex) - mScrollOffsetSecondary;
1091            layoutChild(rowIndex, v, start - mScrollOffsetPrimary, end - mScrollOffsetPrimary,
1092                    startSecondary);
1093            if (DEBUG) {
1094                Log.d(getTag(), "addView " + index + " " + v);
1095            }
1096            updateScrollMin();
1097            updateScrollMax();
1098        }
1099    };
1100
1101    private void layoutChild(int rowIndex, View v, int start, int end, int startSecondary) {
1102        int sizeSecondary = mOrientation == HORIZONTAL ? v.getMeasuredHeight()
1103                : v.getMeasuredWidth();
1104        if (mFixedRowSizeSecondary > 0) {
1105            sizeSecondary = Math.min(sizeSecondary, mFixedRowSizeSecondary);
1106        }
1107        final int verticalGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
1108        final int horizontalGravity = mGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
1109        if (mOrientation == HORIZONTAL && verticalGravity == Gravity.TOP
1110                || mOrientation == VERTICAL && horizontalGravity == Gravity.LEFT) {
1111            // do nothing
1112        } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.BOTTOM
1113                || mOrientation == VERTICAL && horizontalGravity == Gravity.RIGHT) {
1114            startSecondary += getRowSizeSecondary(rowIndex) - sizeSecondary;
1115        } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.CENTER_VERTICAL
1116                || mOrientation == VERTICAL && horizontalGravity == Gravity.CENTER_HORIZONTAL) {
1117            startSecondary += (getRowSizeSecondary(rowIndex) - sizeSecondary) / 2;
1118        }
1119        int left, top, right, bottom;
1120        if (mOrientation == HORIZONTAL) {
1121            left = start;
1122            top = startSecondary;
1123            right = end;
1124            bottom = startSecondary + sizeSecondary;
1125        } else {
1126            top = start;
1127            left = startSecondary;
1128            bottom = end;
1129            right = startSecondary + sizeSecondary;
1130        }
1131        v.layout(left, top, right, bottom);
1132        updateChildOpticalInsets(v, left, top, right, bottom);
1133        updateChildAlignments(v);
1134    }
1135
1136    private void updateChildOpticalInsets(View v, int left, int top, int right, int bottom) {
1137        LayoutParams p = (LayoutParams) v.getLayoutParams();
1138        p.setOpticalInsets(left - v.getLeft(), top - v.getTop(),
1139                v.getRight() - right, v.getBottom() - bottom);
1140    }
1141
1142    private void updateChildAlignments(View v) {
1143        LayoutParams p = (LayoutParams) v.getLayoutParams();
1144        p.setAlignX(mItemAlignment.horizontal.getAlignmentPosition(v));
1145        p.setAlignY(mItemAlignment.vertical.getAlignmentPosition(v));
1146    }
1147
1148    private void updateChildAlignments() {
1149        for (int i = 0, c = getChildCount(); i < c; i++) {
1150            updateChildAlignments(getChildAt(i));
1151        }
1152    }
1153
1154    private boolean needsAppendVisibleItem() {
1155        if (mLastVisiblePos < mFocusPosition) {
1156            return true;
1157        }
1158        int right = mScrollOffsetPrimary + mSizePrimary;
1159        for (int i = 0; i < mNumRows; i++) {
1160            if (mRows[i].low == mRows[i].high) {
1161                if (mRows[i].high < right) {
1162                    return true;
1163                }
1164            } else if (mRows[i].high < right - mMarginPrimary) {
1165                return true;
1166            }
1167        }
1168        return false;
1169    }
1170
1171    private boolean needsPrependVisibleItem() {
1172        if (mFirstVisiblePos > mFocusPosition) {
1173            return true;
1174        }
1175        for (int i = 0; i < mNumRows; i++) {
1176            if (mRows[i].low == mRows[i].high) {
1177                if (mRows[i].low > mScrollOffsetPrimary) {
1178                    return true;
1179                }
1180            } else if (mRows[i].low - mMarginPrimary > mScrollOffsetPrimary) {
1181                return true;
1182            }
1183        }
1184        return false;
1185    }
1186
1187    // Append one column if possible and return true if reach end.
1188    private boolean appendOneVisibleItem() {
1189        while (true) {
1190            if (mLastVisiblePos != NO_POSITION && mLastVisiblePos < mAdapter.getItemCount() -1 &&
1191                    mLastVisiblePos < mGrid.getLastIndex()) {
1192                // append invisible view of saved location till last row
1193                final int index = mLastVisiblePos + 1;
1194                final int row = mGrid.getLocation(index).row;
1195                mGridProvider.createItem(index, row, true);
1196                if (row == mNumRows - 1) {
1197                    return false;
1198                }
1199            } else if ((mLastVisiblePos == NO_POSITION && mAdapter.getItemCount() > 0) ||
1200                    (mLastVisiblePos != NO_POSITION &&
1201                            mLastVisiblePos < mAdapter.getItemCount() - 1)) {
1202                mGrid.appendItems(mScrollOffsetPrimary + mSizePrimary);
1203                return false;
1204            } else {
1205                return true;
1206            }
1207        }
1208    }
1209
1210    private void appendVisibleItems() {
1211        while (needsAppendVisibleItem()) {
1212            if (appendOneVisibleItem()) {
1213                break;
1214            }
1215        }
1216    }
1217
1218    // Prepend one column if possible and return true if reach end.
1219    private boolean prependOneVisibleItem() {
1220        while (true) {
1221            if (mFirstVisiblePos > 0) {
1222                if (mFirstVisiblePos > mGrid.getFirstIndex()) {
1223                    // prepend invisible view of saved location till first row
1224                    final int index = mFirstVisiblePos - 1;
1225                    final int row = mGrid.getLocation(index).row;
1226                    mGridProvider.createItem(index, row, false);
1227                    if (row == 0) {
1228                        return false;
1229                    }
1230                } else {
1231                    mGrid.prependItems(mScrollOffsetPrimary);
1232                    return false;
1233                }
1234            } else {
1235                return true;
1236            }
1237        }
1238    }
1239
1240    private void prependVisibleItems() {
1241        while (needsPrependVisibleItem()) {
1242            if (prependOneVisibleItem()) {
1243                break;
1244            }
1245        }
1246    }
1247
1248    private void removeChildAt(int position) {
1249        View v = getViewByPosition(position);
1250        if (v != null) {
1251            if (DEBUG) {
1252                Log.d(getTag(), "removeAndRecycleViewAt " + position);
1253            }
1254            ((LayoutParams) v.getLayoutParams()).onViewDetached();
1255            removeAndRecycleViewAt(getIndexByPosition(position), mRecycler);
1256        }
1257    }
1258
1259    private void removeInvisibleViewsAtEnd() {
1260        boolean update = false;
1261        while(mLastVisiblePos > mFirstVisiblePos && mLastVisiblePos > mFocusPosition) {
1262            View view = getViewByPosition(mLastVisiblePos);
1263            if (getViewMin(view) > mSizePrimary) {
1264                removeChildAt(mLastVisiblePos);
1265                mLastVisiblePos--;
1266                update = true;
1267            } else {
1268                break;
1269            }
1270        }
1271        if (update) {
1272            updateRowsMinMax();
1273        }
1274    }
1275
1276    private void removeInvisibleViewsAtFront() {
1277        boolean update = false;
1278        while(mLastVisiblePos > mFirstVisiblePos && mFirstVisiblePos < mFocusPosition) {
1279            View view = getViewByPosition(mFirstVisiblePos);
1280            if (getViewMax(view) < 0) {
1281                removeChildAt(mFirstVisiblePos);
1282                mFirstVisiblePos++;
1283                update = true;
1284            } else {
1285                break;
1286            }
1287        }
1288        if (update) {
1289            updateRowsMinMax();
1290        }
1291    }
1292
1293    private void updateRowsMinMax() {
1294        if (mFirstVisiblePos < 0) {
1295            return;
1296        }
1297        for (int i = 0; i < mNumRows; i++) {
1298            mRows[i].low = Integer.MAX_VALUE;
1299            mRows[i].high = Integer.MIN_VALUE;
1300        }
1301        for (int i = mFirstVisiblePos; i <= mLastVisiblePos; i++) {
1302            View view = getViewByPosition(i);
1303            int row = mGrid.getLocation(i).row;
1304            int low = getViewMin(view) + mScrollOffsetPrimary;
1305            if (low < mRows[row].low) {
1306                mRows[row].low = low;
1307            }
1308            int high = getViewMax(view) + mScrollOffsetPrimary;
1309            if (high > mRows[row].high) {
1310                mRows[row].high = high;
1311            }
1312        }
1313    }
1314
1315    /**
1316     * Relayout and re-positioning child for a possible new size and/or a new
1317     * start.
1318     *
1319     * @param view View to measure and layout.
1320     * @param start New start of the view or Integer.MIN_VALUE for not change.
1321     * @return New start of next view.
1322     */
1323    private int updateChildView(int rowIndex, View view, int start) {
1324        if (start == Integer.MIN_VALUE) {
1325            start = getViewMin(view);
1326        }
1327        int end;
1328        if (mOrientation == HORIZONTAL) {
1329            if (view.isLayoutRequested()) {
1330                measureChild(view, rowIndex);
1331            }
1332            end = start + view.getMeasuredWidth();
1333        } else {
1334            if (view.isLayoutRequested()) {
1335                measureChild(view, rowIndex);
1336            }
1337            end = start + view.getMeasuredHeight();
1338        }
1339
1340        final int startSecondary = getRowStartSecondary(rowIndex) - mScrollOffsetSecondary;
1341        layoutChild(rowIndex, view, start, end, startSecondary);
1342        return end + mMarginPrimary;
1343    }
1344
1345    // Fast layout when there is no structure change, adapter change, etc.
1346    protected void fastRelayout() {
1347        initScrollController();
1348
1349        List<Integer>[] rows = mGrid.getItemPositionsInRows(mFirstVisiblePos, mLastVisiblePos);
1350
1351        // relayout and repositioning views on each row
1352        for (int i = 0; i < mNumRows; i++) {
1353            List<Integer> row = rows[i];
1354            int start = Integer.MIN_VALUE;
1355            for (int j = 0, size = row.size(); j < size; j++) {
1356                int position = row.get(j);
1357                start = updateChildView(i, getViewByPosition(position), start);
1358            }
1359        }
1360
1361        appendVisibleItems();
1362        prependVisibleItems();
1363
1364        updateRowsMinMax();
1365        updateScrollMin();
1366        updateScrollMax();
1367        updateScrollSecondAxis();
1368
1369        if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
1370            View focusView = getViewByPosition(mFocusPosition == NO_POSITION ? 0 : mFocusPosition);
1371            scrollToView(focusView, false);
1372        }
1373    }
1374
1375    // Lays out items based on the current scroll position
1376    @Override
1377    public void onLayoutChildren(RecyclerView.Adapter adapter, RecyclerView.Recycler recycler,
1378            boolean structureChanged, RecyclerView.State state) {
1379        if (DEBUG) {
1380            Log.v(getTag(), "layoutChildren start numRows " + mNumRows + " mScrollOffsetSecondary "
1381                    + mScrollOffsetSecondary + " mScrollOffsetPrimary " + mScrollOffsetPrimary
1382                    + " structureChanged " + structureChanged
1383                    + " mForceFullLayout " + mForceFullLayout);
1384            Log.v(getTag(), "width " + getWidth() + " height " + getHeight());
1385        }
1386
1387        if (mNumRows == 0) {
1388            // haven't done measure yet
1389            return;
1390        }
1391        final int itemCount = adapter.getItemCount();
1392        if (itemCount < 0) {
1393            return;
1394        }
1395
1396        mInLayout = true;
1397
1398        // Track the old focus view so we can adjust our system scroll position
1399        // so that any scroll animations happening now will remain valid.
1400        int delta = 0, deltaSecondary = 0;
1401        if (mFocusPosition != NO_POSITION
1402                && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
1403            View focusView = getViewByPosition(mFocusPosition);
1404            if (focusView != null) {
1405                delta = mWindowAlignment.mainAxis().getSystemScrollPos(
1406                        getViewCenter(focusView) + mScrollOffsetPrimary) - mScrollOffsetPrimary;
1407                deltaSecondary =
1408                    mWindowAlignment.secondAxis().getSystemScrollPos(
1409                            getViewCenterSecondary(focusView) + mScrollOffsetSecondary)
1410                    - mScrollOffsetSecondary;
1411            }
1412        }
1413
1414        boolean hasDoneFirstLayout = hasDoneFirstLayout();
1415        if (!structureChanged && !mForceFullLayout && hasDoneFirstLayout) {
1416            fastRelayout();
1417        } else {
1418            boolean hadFocus = mBaseGridView.hasFocus();
1419
1420            int newFocusPosition = init(adapter, recycler, mFocusPosition);
1421            if (DEBUG) {
1422                Log.v(getTag(), "mFocusPosition " + mFocusPosition + " newFocusPosition "
1423                    + newFocusPosition);
1424            }
1425
1426            // depending on result of init(), either recreating everything
1427            // or try to reuse the row start positions near mFocusPosition
1428            if (mGrid.getSize() == 0) {
1429                // this is a fresh creating all items, starting from
1430                // mFocusPosition with a estimated row index.
1431                mGrid.setStart(newFocusPosition, StaggeredGrid.START_DEFAULT);
1432
1433                // Can't track the old focus view
1434                delta = deltaSecondary = 0;
1435
1436            } else {
1437                // mGrid remembers Locations for the column that
1438                // contains mFocusePosition and also mRows remembers start
1439                // positions of each row.
1440                // Manually re-create child views for that column
1441                int firstIndex = mGrid.getFirstIndex();
1442                int lastIndex = mGrid.getLastIndex();
1443                for (int i = firstIndex; i <= lastIndex; i++) {
1444                    mGridProvider.createItem(i, mGrid.getLocation(i).row, true);
1445                }
1446            }
1447            // add visible views at end until reach the end of window
1448            appendVisibleItems();
1449            // add visible views at front until reach the start of window
1450            prependVisibleItems();
1451            // multiple rounds: scrollToView of first round may drag first/last child into
1452            // "visible window" and we update scrollMin/scrollMax then run second scrollToView
1453            int oldFirstVisible;
1454            int oldLastVisible;
1455            do {
1456                oldFirstVisible = mFirstVisiblePos;
1457                oldLastVisible = mLastVisiblePos;
1458                View focusView = getViewByPosition(newFocusPosition);
1459                // we need force to initialize the child view's position
1460                scrollToView(focusView, false);
1461                if (focusView != null && hadFocus) {
1462                    focusView.requestFocus();
1463                }
1464                appendVisibleItems();
1465                prependVisibleItems();
1466                removeInvisibleViewsAtFront();
1467                removeInvisibleViewsAtEnd();
1468            } while (mFirstVisiblePos != oldFirstVisible || mLastVisiblePos != oldLastVisible);
1469        }
1470        mForceFullLayout = false;
1471
1472        if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
1473            scrollDirectionPrimary(-delta);
1474            scrollDirectionSecondary(-deltaSecondary);
1475        }
1476        appendVisibleItems();
1477        prependVisibleItems();
1478        removeInvisibleViewsAtFront();
1479        removeInvisibleViewsAtEnd();
1480
1481        if (DEBUG) {
1482            StringWriter sw = new StringWriter();
1483            PrintWriter pw = new PrintWriter(sw);
1484            mGrid.debugPrint(pw);
1485            Log.d(getTag(), sw.toString());
1486        }
1487
1488        removeAndRecycleScrap(recycler);
1489        attemptAnimateLayoutChild();
1490
1491        if (mRowSecondarySizeRefresh) {
1492            mRowSecondarySizeRefresh = false;
1493        } else {
1494            updateRowSecondarySizeRefresh();
1495        }
1496
1497        if (!hasDoneFirstLayout) {
1498            dispatchChildSelected();
1499        }
1500        mInLayout = false;
1501        if (DEBUG) Log.v(getTag(), "layoutChildren end");
1502    }
1503
1504    private void offsetChildrenSecondary(int increment) {
1505        final int childCount = getChildCount();
1506        if (mOrientation == HORIZONTAL) {
1507            for (int i = 0; i < childCount; i++) {
1508                getChildAt(i).offsetTopAndBottom(increment);
1509            }
1510        } else {
1511            for (int i = 0; i < childCount; i++) {
1512                getChildAt(i).offsetLeftAndRight(increment);
1513            }
1514        }
1515        mScrollOffsetSecondary -= increment;
1516    }
1517
1518    private void offsetChildrenPrimary(int increment) {
1519        final int childCount = getChildCount();
1520        if (mOrientation == VERTICAL) {
1521            for (int i = 0; i < childCount; i++) {
1522                getChildAt(i).offsetTopAndBottom(increment);
1523            }
1524        } else {
1525            for (int i = 0; i < childCount; i++) {
1526                getChildAt(i).offsetLeftAndRight(increment);
1527            }
1528        }
1529        mScrollOffsetPrimary -= increment;
1530    }
1531
1532    @Override
1533    public int scrollHorizontallyBy(int dx, Adapter adapter, Recycler recycler,
1534            RecyclerView.State state) {
1535        if (DEBUG) Log.v(TAG, "scrollHorizontallyBy " + dx);
1536
1537        if (mOrientation == HORIZONTAL) {
1538            return scrollDirectionPrimary(dx);
1539        } else {
1540            return scrollDirectionSecondary(dx);
1541        }
1542    }
1543
1544    @Override
1545    public int scrollVerticallyBy(int dy, Adapter adapter, Recycler recycler,
1546            RecyclerView.State state) {
1547        if (DEBUG) Log.v(TAG, "scrollVerticallyBy " + dy);
1548        if (mOrientation == VERTICAL) {
1549            return scrollDirectionPrimary(dy);
1550        } else {
1551            return scrollDirectionSecondary(dy);
1552        }
1553    }
1554
1555    // scroll in main direction may add/prune views
1556    private int scrollDirectionPrimary(int da) {
1557        offsetChildrenPrimary(-da);
1558        if (mInLayout) {
1559            return da;
1560        }
1561
1562        int childCount = getChildCount();
1563        boolean updated;
1564
1565        if (da > 0) {
1566            appendVisibleItems();
1567        } else if (da < 0) {
1568            prependVisibleItems();
1569        }
1570        updated = getChildCount() > childCount;
1571        childCount = getChildCount();
1572
1573        if (da > 0) {
1574            removeInvisibleViewsAtFront();
1575        } else if (da < 0) {
1576            removeInvisibleViewsAtEnd();
1577        }
1578        updated |= getChildCount() < childCount;
1579
1580        attemptAnimateLayoutChild();
1581        if (updated) {
1582            updateRowSecondarySizeRefresh();
1583        }
1584
1585        mBaseGridView.invalidate();
1586        return da;
1587    }
1588
1589    // scroll in second direction will not add/prune views
1590    private int scrollDirectionSecondary(int dy) {
1591        offsetChildrenSecondary(-dy);
1592        mBaseGridView.invalidate();
1593        return dy;
1594    }
1595
1596    private void updateScrollMax() {
1597        if (mLastVisiblePos >= 0 && mLastVisiblePos == mAdapter.getItemCount() - 1) {
1598            int maxEdge = Integer.MIN_VALUE;
1599            for (int i = 0; i < mRows.length; i++) {
1600                if (mRows[i].high > maxEdge) {
1601                    maxEdge = mRows[i].high;
1602                }
1603            }
1604            mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1605            if (DEBUG) Log.v(getTag(), "updating scroll maxEdge to " + maxEdge);
1606        }
1607    }
1608
1609    private void updateScrollMin() {
1610        if (mFirstVisiblePos == 0) {
1611            int minEdge = Integer.MAX_VALUE;
1612            for (int i = 0; i < mRows.length; i++) {
1613                if (mRows[i].low < minEdge) {
1614                    minEdge = mRows[i].low;
1615                }
1616            }
1617            mWindowAlignment.mainAxis().setMinEdge(minEdge);
1618            if (DEBUG) Log.v(getTag(), "updating scroll minEdge to " + minEdge);
1619        }
1620    }
1621
1622    private void updateScrollSecondAxis() {
1623        mWindowAlignment.secondAxis().setMinEdge(0);
1624        mWindowAlignment.secondAxis().setMaxEdge(getSizeSecondary());
1625    }
1626
1627    private void initScrollController() {
1628        mWindowAlignment.horizontal.setSize(getWidth());
1629        mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight());
1630        mWindowAlignment.vertical.setSize(getHeight());
1631        mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom());
1632        mSizePrimary = mWindowAlignment.mainAxis().getSize();
1633        mWindowAlignment.mainAxis().invalidateScrollMin();
1634        mWindowAlignment.mainAxis().invalidateScrollMax();
1635
1636        if (DEBUG) {
1637            Log.v(getTag(), "initScrollController mSizePrimary " + mSizePrimary
1638                    + " mWindowAlignment " + mWindowAlignment);
1639        }
1640    }
1641
1642    public void setSelection(RecyclerView parent, int position) {
1643        setSelection(parent, position, false);
1644    }
1645
1646    public void setSelectionSmooth(RecyclerView parent, int position) {
1647        setSelection(parent, position, true);
1648    }
1649
1650    public int getSelection() {
1651        return mFocusPosition;
1652    }
1653
1654    public void setSelection(RecyclerView parent, int position, boolean smooth) {
1655        if (mFocusPosition == position) {
1656            return;
1657        }
1658        View view = getViewByPosition(position);
1659        if (view != null) {
1660            scrollToView(view, smooth);
1661        } else {
1662            boolean right = position > mFocusPosition;
1663            mFocusPosition = position;
1664            if (smooth) {
1665                if (!hasDoneFirstLayout()) {
1666                    Log.w(getTag(), "setSelectionSmooth should " +
1667                            "not be called before first layout pass");
1668                    return;
1669                }
1670                if (right) {
1671                    appendVisibleItems();
1672                } else {
1673                    prependVisibleItems();
1674                }
1675                scrollToView(getViewByPosition(position), smooth);
1676            } else {
1677                mForceFullLayout = true;
1678                parent.requestLayout();
1679            }
1680        }
1681    }
1682
1683    @Override
1684    public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
1685        boolean needsLayout = false;
1686        if (itemCount != 0) {
1687            if (mFirstVisiblePos < 0) {
1688                needsLayout = true;
1689            } else if (!(positionStart > mLastVisiblePos + 1 ||
1690                    positionStart + itemCount < mFirstVisiblePos - 1)) {
1691                needsLayout = true;
1692            }
1693        }
1694        if (needsLayout) {
1695            recyclerView.requestLayout();
1696        }
1697    }
1698
1699    @Override
1700    public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) {
1701        if (mFocusSearchDisabled) {
1702            return true;
1703        }
1704        if (!mInLayout) {
1705            scrollToView(child, true);
1706        }
1707        return true;
1708    }
1709
1710    @Override
1711    public boolean requestChildRectangleOnScreen(RecyclerView parent, View view, Rect rect,
1712            boolean immediate) {
1713        if (DEBUG) Log.v(getTag(), "requestChildRectangleOnScreen " + view + " " + rect);
1714        return false;
1715    }
1716
1717    int getScrollOffsetX() {
1718        return mOrientation == HORIZONTAL ? mScrollOffsetPrimary : mScrollOffsetSecondary;
1719    }
1720
1721    int getScrollOffsetY() {
1722        return mOrientation == HORIZONTAL ? mScrollOffsetSecondary : mScrollOffsetPrimary;
1723    }
1724
1725    public void getViewSelectedOffsets(View view, int[] offsets) {
1726        int scrollOffsetX = getScrollOffsetX();
1727        int scrollOffsetY = getScrollOffsetY();
1728        int viewCenterX = scrollOffsetX + getViewCenterX(view);
1729        int viewCenterY = scrollOffsetY + getViewCenterY(view);
1730        offsets[0] = mWindowAlignment.horizontal.getSystemScrollPos(viewCenterX) - scrollOffsetX;
1731        offsets[1] = mWindowAlignment.vertical.getSystemScrollPos(viewCenterY) - scrollOffsetY;
1732    }
1733
1734    /**
1735     * Scroll to a given child view and change mFocusPosition.
1736     */
1737    private void scrollToView(View view, boolean smooth) {
1738        int newFocusPosition = getPositionByView(view);
1739        if (mInLayout || newFocusPosition != mFocusPosition) {
1740            mFocusPosition = newFocusPosition;
1741            dispatchChildSelected();
1742        }
1743        if (mBaseGridView.isChildrenDrawingOrderEnabledInternal()) {
1744            mBaseGridView.invalidate();
1745        }
1746        if (view == null) {
1747            return;
1748        }
1749        if (!view.hasFocus() && mBaseGridView.hasFocus()) {
1750            // transfer focus to the child if it does not have focus yet (e.g. triggered
1751            // by setSelection())
1752            view.requestFocus();
1753        }
1754        switch (mFocusScrollStrategy) {
1755        case BaseGridView.FOCUS_SCROLL_ALIGNED:
1756        default:
1757            scrollToAlignedPosition(view, smooth);
1758            break;
1759        case BaseGridView.FOCUS_SCROLL_ITEM:
1760        case BaseGridView.FOCUS_SCROLL_PAGE:
1761            scrollItemOrPage(view, smooth);
1762            break;
1763        }
1764    }
1765
1766    private void scrollItemOrPage(View view, boolean smooth) {
1767        int pos = getPositionByView(view);
1768        int viewMin = getViewMin(view);
1769        int viewMax = getViewMax(view);
1770        // we either align "firstView" to left/top padding edge
1771        // or align "lastView" to right/bottom padding edge
1772        View firstView = null;
1773        View lastView = null;
1774        int paddingLow = mWindowAlignment.mainAxis().getPaddingLow();
1775        int clientSize = mWindowAlignment.mainAxis().getClientSize();
1776        final int row = mGrid.getLocation(pos).row;
1777        if (viewMin < paddingLow) {
1778            // view enters low padding area:
1779            firstView = view;
1780            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
1781                // scroll one "page" left/top,
1782                // align first visible item of the "page" at the low padding edge.
1783                while (!prependOneVisibleItem()) {
1784                    List<Integer> positions =
1785                            mGrid.getItemPositionsInRows(mFirstVisiblePos, pos)[row];
1786                    firstView = getViewByPosition(positions.get(0));
1787                    if (viewMax - getViewMin(firstView) > clientSize) {
1788                        if (positions.size() > 1) {
1789                            firstView = getViewByPosition(positions.get(1));
1790                        }
1791                        break;
1792                    }
1793                }
1794            }
1795        } else if (viewMax > clientSize + paddingLow) {
1796            // view enters high padding area:
1797            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
1798                // scroll whole one page right/bottom, align view at the low padding edge.
1799                firstView = view;
1800                do {
1801                    List<Integer> positions =
1802                            mGrid.getItemPositionsInRows(pos, mLastVisiblePos)[row];
1803                    lastView = getViewByPosition(positions.get(positions.size() - 1));
1804                    if (getViewMax(lastView) - viewMin > clientSize) {
1805                        lastView = null;
1806                        break;
1807                    }
1808                } while (!appendOneVisibleItem());
1809                if (lastView != null) {
1810                    // however if we reached end,  we should align last view.
1811                    firstView = null;
1812                }
1813            } else {
1814                lastView = view;
1815            }
1816        }
1817        int scrollPrimary = 0;
1818        int scrollSecondary = 0;
1819        if (firstView != null) {
1820            scrollPrimary = getViewMin(firstView) - paddingLow;
1821        } else if (lastView != null) {
1822            scrollPrimary = getViewMax(lastView) - (paddingLow + clientSize);
1823        }
1824        View secondaryAlignedView;
1825        if (firstView != null) {
1826            secondaryAlignedView = firstView;
1827        } else if (lastView != null) {
1828            secondaryAlignedView = lastView;
1829        } else {
1830            secondaryAlignedView = view;
1831        }
1832        int viewCenterSecondary = mScrollOffsetSecondary +
1833                getViewCenterSecondary(secondaryAlignedView);
1834        mWindowAlignment.secondAxis().updateScrollCenter(viewCenterSecondary);
1835        scrollSecondary = mWindowAlignment.secondAxis().getSystemScrollPos();
1836        scrollSecondary -= mScrollOffsetSecondary;
1837        scrollGrid(scrollPrimary, scrollSecondary, smooth);
1838    }
1839
1840    private void scrollToAlignedPosition(View view, boolean smooth) {
1841        int viewCenterPrimary = mScrollOffsetPrimary + getViewCenter(view);
1842        int viewCenterSecondary = mScrollOffsetSecondary + getViewCenterSecondary(view);
1843        if (DEBUG) {
1844            Log.v(getTag(), "scrollAligned smooth=" + smooth + " pos=" + mFocusPosition + " "
1845                    + viewCenterPrimary +","+viewCenterSecondary + " " + mWindowAlignment);
1846        }
1847
1848        if (mInLayout || viewCenterPrimary != mWindowAlignment.mainAxis().getScrollCenter()
1849                || viewCenterSecondary != mWindowAlignment.secondAxis().getScrollCenter()) {
1850            mWindowAlignment.mainAxis().updateScrollCenter(viewCenterPrimary);
1851            mWindowAlignment.secondAxis().updateScrollCenter(viewCenterSecondary);
1852            int scrollPrimary = mWindowAlignment.mainAxis().getSystemScrollPos();
1853            int scrollSecondary = mWindowAlignment.secondAxis().getSystemScrollPos();
1854            if (DEBUG) {
1855                Log.v(getTag(), "scrollAligned " + scrollPrimary + " " + scrollSecondary
1856                        +" " + mWindowAlignment);
1857            }
1858
1859            scrollPrimary -= mScrollOffsetPrimary;
1860            scrollSecondary -= mScrollOffsetSecondary;
1861
1862            scrollGrid(scrollPrimary, scrollSecondary, smooth);
1863        }
1864    }
1865
1866    private void scrollGrid(int scrollPrimary, int scrollSecondary, boolean smooth) {
1867        if (mInLayout) {
1868            scrollDirectionPrimary(scrollPrimary);
1869            scrollDirectionSecondary(scrollSecondary);
1870        } else {
1871            int scrollX;
1872            int scrollY;
1873            if (mOrientation == HORIZONTAL) {
1874                scrollX = scrollPrimary;
1875                scrollY = scrollSecondary;
1876            } else {
1877                scrollX = scrollSecondary;
1878                scrollY = scrollPrimary;
1879            }
1880            if (smooth) {
1881                mBaseGridView.smoothScrollBy(scrollX, scrollY);
1882            } else {
1883                mBaseGridView.scrollBy(scrollX, scrollY);
1884            }
1885        }
1886    }
1887
1888    public void setAnimateChildLayout(boolean animateChildLayout) {
1889        mAnimateChildLayout = animateChildLayout;
1890        for (int i = 0, c = getChildCount(); i < c; i++) {
1891            View v = getChildAt(i);
1892            LayoutParams p = (LayoutParams) v.getLayoutParams();
1893            if (!mAnimateChildLayout) {
1894                p.endAnimate();
1895            } else {
1896                // record initial location values
1897                p.mFirstAttached = true;
1898                p.startAnimate(this, v, 0);
1899            }
1900        }
1901    }
1902
1903    private void attemptAnimateLayoutChild() {
1904        if (!mAnimateChildLayout) {
1905            return;
1906        }
1907        for (int i = 0, c = getChildCount(); i < c; i++) {
1908            // TODO: start delay can be staggered
1909            View v = getChildAt(i);
1910            ((LayoutParams) v.getLayoutParams()).startAnimate(this, v, 0);
1911        }
1912    }
1913
1914    public boolean isChildLayoutAnimated() {
1915        return mAnimateChildLayout;
1916    }
1917
1918    public void setChildLayoutAnimationInterpolator(Interpolator interpolator) {
1919        mAnimateLayoutChildInterpolator = interpolator;
1920    }
1921
1922    public Interpolator getChildLayoutAnimationInterpolator() {
1923        return mAnimateLayoutChildInterpolator;
1924    }
1925
1926    public void setChildLayoutAnimationDuration(long duration) {
1927        mAnimateLayoutChildDuration = duration;
1928    }
1929
1930    public long getChildLayoutAnimationDuration() {
1931        return mAnimateLayoutChildDuration;
1932    }
1933
1934    private int findImmediateChildIndex(View view) {
1935        while (view != null && view != mBaseGridView) {
1936            int index = mBaseGridView.indexOfChild(view);
1937            if (index >= 0) {
1938                return index;
1939            }
1940            view = (View) view.getParent();
1941        }
1942        return NO_POSITION;
1943    }
1944
1945    void setFocusSearchDisabled(boolean disabled) {
1946        mFocusSearchDisabled = disabled;
1947    }
1948
1949    boolean isFocusSearchDisabled() {
1950        return mFocusSearchDisabled;
1951    }
1952
1953    @Override
1954    public View onInterceptFocusSearch(View focused, int direction) {
1955        if (mFocusSearchDisabled) {
1956            return focused;
1957        }
1958        return null;
1959    }
1960
1961    boolean hasNextViewInSameRow(int pos) {
1962        if (mGrid == null || pos == NO_POSITION) {
1963            return false;
1964        }
1965        final int focusedRow = mGrid.getLocation(pos).row;
1966        for (int i = 0, count = getChildCount(); i < count; i++) {
1967            int position = getPositionByIndex(i);
1968            StaggeredGrid.Location loc = mGrid.getLocation(position);
1969            if (loc != null && loc.row == focusedRow) {
1970                if (position > pos) {
1971                    return true;
1972                }
1973            }
1974        }
1975        return false;
1976    }
1977
1978    boolean hasPreviousViewInSameRow(int pos) {
1979        if (mGrid == null || pos == NO_POSITION) {
1980            return false;
1981        }
1982        final int focusedRow = mGrid.getLocation(pos).row;
1983        for (int i = getChildCount() - 1; i >= 0; i--) {
1984            int position = getPositionByIndex(i);
1985            StaggeredGrid.Location loc = mGrid.getLocation(position);
1986            if (loc != null && loc.row == focusedRow) {
1987                if (position < pos) {
1988                    return true;
1989                }
1990            }
1991        }
1992        return false;
1993    }
1994
1995    @Override
1996    public boolean onAddFocusables(RecyclerView recyclerView,
1997            ArrayList<View> views, int direction, int focusableMode) {
1998        if (mFocusSearchDisabled) {
1999            return true;
2000        }
2001        // If this viewgroup or one of its children currently has focus then we
2002        // consider our children for focus searching in main direction on the same row.
2003        // If this viewgroup has no focus and using focus align, we want the system
2004        // to ignore our children and pass focus to the viewgroup, which will pass
2005        // focus on to its children appropriately.
2006        // If this viewgroup has no focus and not using focus align, we want to
2007        // consider the child that does not overlap with padding area.
2008        if (recyclerView.hasFocus()) {
2009            final int movement = getMovement(direction);
2010            if (movement != PREV_ITEM && movement != NEXT_ITEM) {
2011                // Move on secondary direction uses default addFocusables().
2012                return false;
2013            }
2014            final View focused = recyclerView.findFocus();
2015            final int focusedPos = getPositionByIndex(findImmediateChildIndex(focused));
2016            // Add focusables of focused item.
2017            if (focusedPos != NO_POSITION) {
2018                getViewByPosition(focusedPos).addFocusables(views,  direction, focusableMode);
2019            }
2020            final int focusedRow = mGrid != null && focusedPos != NO_POSITION ?
2021                    mGrid.getLocation(focusedPos).row : NO_POSITION;
2022            // Add focusables of next neighbor of same row on the focus search direction.
2023            if (mGrid != null) {
2024                final int focusableCount = views.size();
2025                for (int i = 0, count = getChildCount(); i < count; i++) {
2026                    int index = movement == NEXT_ITEM ? i : count - 1 - i;
2027                    final View child = getChildAt(index);
2028                    if (child.getVisibility() != View.VISIBLE) {
2029                        continue;
2030                    }
2031                    int position = getPositionByIndex(index);
2032                    StaggeredGrid.Location loc = mGrid.getLocation(position);
2033                    if (focusedRow == NO_POSITION || (loc != null && loc.row == focusedRow)) {
2034                        if (focusedPos == NO_POSITION ||
2035                                (movement == NEXT_ITEM && position > focusedPos)
2036                                || (movement == PREV_ITEM && position < focusedPos)) {
2037                            child.addFocusables(views,  direction, focusableMode);
2038                            if (views.size() > focusableCount) {
2039                                break;
2040                            }
2041                        }
2042                    }
2043                }
2044            }
2045        } else {
2046            if (mFocusScrollStrategy != BaseGridView.FOCUS_SCROLL_ALIGNED) {
2047                // adding views not overlapping padding area to avoid scrolling in gaining focus
2048                int left = mWindowAlignment.mainAxis().getPaddingLow();
2049                int right = mWindowAlignment.mainAxis().getClientSize() + left;
2050                int focusableCount = views.size();
2051                for (int i = 0, count = getChildCount(); i < count; i++) {
2052                    View child = getChildAt(i);
2053                    if (child.getVisibility() == View.VISIBLE) {
2054                        if (getViewMin(child) >= left && getViewMax(child) <= right) {
2055                            child.addFocusables(views, direction, focusableMode);
2056                        }
2057                    }
2058                }
2059                // if we cannot find any, then just add all children.
2060                if (views.size() == focusableCount) {
2061                    for (int i = 0, count = getChildCount(); i < count; i++) {
2062                        View child = getChildAt(i);
2063                        if (child.getVisibility() == View.VISIBLE) {
2064                            child.addFocusables(views, direction, focusableMode);
2065                        }
2066                    }
2067                    if (views.size() != focusableCount) {
2068                        return true;
2069                    }
2070                } else {
2071                    return true;
2072                }
2073                // if still cannot find any, fall through and add itself
2074            }
2075            if (recyclerView.isFocusable()) {
2076                views.add(recyclerView);
2077            }
2078        }
2079        return true;
2080    }
2081
2082    @Override
2083    public View onFocusSearchFailed(View focused, int direction, Adapter adapter,
2084            Recycler recycler) {
2085        if (DEBUG) Log.v(getTag(), "onFocusSearchFailed direction " + direction);
2086
2087        View view = null;
2088        int movement = getMovement(direction);
2089        final FocusFinder ff = FocusFinder.getInstance();
2090        if (movement == NEXT_ITEM) {
2091            while (view == null && !appendOneVisibleItem()) {
2092                view = ff.findNextFocus(mBaseGridView, focused, direction);
2093            }
2094        } else if (movement == PREV_ITEM){
2095            while (view == null && !prependOneVisibleItem()) {
2096                view = ff.findNextFocus(mBaseGridView, focused, direction);
2097            }
2098        }
2099        if (view == null) {
2100            // returning the same view to prevent focus lost when scrolling past the end of the list
2101            if (movement == PREV_ITEM) {
2102                view = mFocusOutFront ? null : focused;
2103            } else if (movement == NEXT_ITEM){
2104                view = mFocusOutEnd ? null : focused;
2105            }
2106        }
2107        if (DEBUG) Log.v(getTag(), "returning view " + view);
2108        return view;
2109    }
2110
2111    boolean gridOnRequestFocusInDescendants(RecyclerView recyclerView, int direction,
2112            Rect previouslyFocusedRect) {
2113        switch (mFocusScrollStrategy) {
2114        case BaseGridView.FOCUS_SCROLL_ALIGNED:
2115        default:
2116            return gridOnRequestFocusInDescendantsAligned(recyclerView,
2117                    direction, previouslyFocusedRect);
2118        case BaseGridView.FOCUS_SCROLL_PAGE:
2119        case BaseGridView.FOCUS_SCROLL_ITEM:
2120            return gridOnRequestFocusInDescendantsUnaligned(recyclerView,
2121                    direction, previouslyFocusedRect);
2122        }
2123    }
2124
2125    private boolean gridOnRequestFocusInDescendantsAligned(RecyclerView recyclerView,
2126            int direction, Rect previouslyFocusedRect) {
2127        View view = getViewByPosition(mFocusPosition);
2128        if (view != null) {
2129            boolean result = view.requestFocus(direction, previouslyFocusedRect);
2130            if (!result && DEBUG) {
2131                Log.w(getTag(), "failed to request focus on " + view);
2132            }
2133            return result;
2134        }
2135        return false;
2136    }
2137
2138    private boolean gridOnRequestFocusInDescendantsUnaligned(RecyclerView recyclerView,
2139            int direction, Rect previouslyFocusedRect) {
2140        // focus to view not overlapping padding area to avoid scrolling in gaining focus
2141        int index;
2142        int increment;
2143        int end;
2144        int count = getChildCount();
2145        if ((direction & View.FOCUS_FORWARD) != 0) {
2146            index = 0;
2147            increment = 1;
2148            end = count;
2149        } else {
2150            index = count - 1;
2151            increment = -1;
2152            end = -1;
2153        }
2154        int left = mWindowAlignment.mainAxis().getPaddingLow();
2155        int right = mWindowAlignment.mainAxis().getClientSize() + left;
2156        for (int i = index; i != end; i += increment) {
2157            View child = getChildAt(i);
2158            if (child.getVisibility() == View.VISIBLE) {
2159                if (getViewMin(child) >= left && getViewMax(child) <= right) {
2160                    if (child.requestFocus(direction, previouslyFocusedRect)) {
2161                        return true;
2162                    }
2163                }
2164            }
2165        }
2166        return false;
2167    }
2168
2169    private final static int PREV_ITEM = 0;
2170    private final static int NEXT_ITEM = 1;
2171    private final static int PREV_ROW = 2;
2172    private final static int NEXT_ROW = 3;
2173
2174    private int getMovement(int direction) {
2175        int movement = View.FOCUS_LEFT;
2176
2177        if (mOrientation == HORIZONTAL) {
2178            switch(direction) {
2179                case View.FOCUS_LEFT:
2180                    movement = PREV_ITEM;
2181                    break;
2182                case View.FOCUS_RIGHT:
2183                    movement = NEXT_ITEM;
2184                    break;
2185                case View.FOCUS_UP:
2186                    movement = PREV_ROW;
2187                    break;
2188                case View.FOCUS_DOWN:
2189                    movement = NEXT_ROW;
2190                    break;
2191            }
2192         } else if (mOrientation == VERTICAL) {
2193             switch(direction) {
2194                 case View.FOCUS_LEFT:
2195                     movement = PREV_ROW;
2196                     break;
2197                 case View.FOCUS_RIGHT:
2198                     movement = NEXT_ROW;
2199                     break;
2200                 case View.FOCUS_UP:
2201                     movement = PREV_ITEM;
2202                     break;
2203                 case View.FOCUS_DOWN:
2204                     movement = NEXT_ITEM;
2205                     break;
2206             }
2207         }
2208
2209        return movement;
2210    }
2211
2212    int getChildDrawingOrder(RecyclerView recyclerView, int childCount, int i) {
2213        int focusIndex = getIndexByPosition(mFocusPosition);
2214        if (focusIndex == NO_POSITION) {
2215            return i;
2216        }
2217        // supposely 0 1 2 3 4 5 6 7 8 9, 4 is the center item
2218        // drawing order is 0 1 2 3 9 8 7 6 5 4
2219        if (i < focusIndex) {
2220            return i;
2221        } else if (i < childCount - 1) {
2222            return focusIndex + childCount - 1 - i;
2223        } else {
2224            return focusIndex;
2225        }
2226    }
2227
2228    @Override
2229    public void onAdapterChanged(RecyclerView.Adapter oldAdapter,
2230            RecyclerView.Adapter newAdapter) {
2231        mGrid = null;
2232        mRows = null;
2233        mRowSizeSecondary = null;
2234        mRowSecondarySizeRefresh = false;
2235        super.onAdapterChanged(oldAdapter, newAdapter);
2236    }
2237}
2238