GridLayoutManager.java revision 3a7aa9cd68bd39f3a843291817dc209d1d9a45aa
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.content.Context;
17import android.graphics.PointF;
18import android.graphics.Rect;
19import android.os.Bundle;
20import android.os.Parcel;
21import android.os.Parcelable;
22import android.support.v4.util.CircularIntArray;
23import android.support.v4.view.ViewCompat;
24import android.support.v7.widget.LinearSmoothScroller;
25import android.support.v7.widget.RecyclerView;
26import android.support.v7.widget.RecyclerView.Recycler;
27import android.support.v7.widget.RecyclerView.State;
28import android.support.v17.leanback.os.TraceHelper;
29
30import static android.support.v7.widget.RecyclerView.NO_ID;
31import static android.support.v7.widget.RecyclerView.NO_POSITION;
32import static android.support.v7.widget.RecyclerView.HORIZONTAL;
33import static android.support.v7.widget.RecyclerView.VERTICAL;
34
35import android.util.AttributeSet;
36import android.util.Log;
37import android.view.FocusFinder;
38import android.view.Gravity;
39import android.view.View;
40import android.view.ViewParent;
41import android.view.View.MeasureSpec;
42import android.view.ViewGroup.MarginLayoutParams;
43import android.view.ViewGroup;
44
45import java.io.PrintWriter;
46import java.io.StringWriter;
47import java.util.ArrayList;
48import java.util.List;
49
50final class GridLayoutManager extends RecyclerView.LayoutManager {
51
52     /*
53      * LayoutParams for {@link HorizontalGridView} and {@link VerticalGridView}.
54      * The class currently does two internal jobs:
55      * - Saves optical bounds insets.
56      * - Caches focus align view center.
57      */
58    static class LayoutParams extends RecyclerView.LayoutParams {
59
60        // The view is saved only during animation.
61        private View mView;
62
63        // For placement
64        private int mLeftInset;
65        private int mTopInset;
66        private int mRightInset;
67        private int mBottomInset;
68
69        // For alignment
70        private int mAlignX;
71        private int mAlignY;
72
73        public LayoutParams(Context c, AttributeSet attrs) {
74            super(c, attrs);
75        }
76
77        public LayoutParams(int width, int height) {
78            super(width, height);
79        }
80
81        public LayoutParams(MarginLayoutParams source) {
82            super(source);
83        }
84
85        public LayoutParams(ViewGroup.LayoutParams source) {
86            super(source);
87        }
88
89        public LayoutParams(RecyclerView.LayoutParams source) {
90            super(source);
91        }
92
93        public LayoutParams(LayoutParams source) {
94            super(source);
95        }
96
97        int getAlignX() {
98            return mAlignX;
99        }
100
101        int getAlignY() {
102            return mAlignY;
103        }
104
105        int getOpticalLeft(View view) {
106            return view.getLeft() + mLeftInset;
107        }
108
109        int getOpticalTop(View view) {
110            return view.getTop() + mTopInset;
111        }
112
113        int getOpticalRight(View view) {
114            return view.getRight() - mRightInset;
115        }
116
117        int getOpticalBottom(View view) {
118            return view.getBottom() - mBottomInset;
119        }
120
121        int getOpticalWidth(View view) {
122            return view.getWidth() - mLeftInset - mRightInset;
123        }
124
125        int getOpticalHeight(View view) {
126            return view.getHeight() - mTopInset - mBottomInset;
127        }
128
129        int getOpticalLeftInset() {
130            return mLeftInset;
131        }
132
133        int getOpticalRightInset() {
134            return mRightInset;
135        }
136
137        int getOpticalTopInset() {
138            return mTopInset;
139        }
140
141        int getOpticalBottomInset() {
142            return mBottomInset;
143        }
144
145        void setAlignX(int alignX) {
146            mAlignX = alignX;
147        }
148
149        void setAlignY(int alignY) {
150            mAlignY = alignY;
151        }
152
153        void setOpticalInsets(int leftInset, int topInset, int rightInset, int bottomInset) {
154            mLeftInset = leftInset;
155            mTopInset = topInset;
156            mRightInset = rightInset;
157            mBottomInset = bottomInset;
158        }
159
160        private void invalidateItemDecoration() {
161            ViewParent parent = mView.getParent();
162            if (parent instanceof RecyclerView) {
163                // TODO: we only need invalidate parent if it has ItemDecoration
164                ((RecyclerView) parent).invalidate();
165            }
166        }
167    }
168
169    /**
170     * Base class which scrolls to selected view in onStop().
171     */
172    abstract class GridLinearSmoothScroller extends LinearSmoothScroller {
173        GridLinearSmoothScroller() {
174            super(mBaseGridView.getContext());
175        }
176
177        @Override
178        protected void onStop() {
179            // onTargetFound() may not be called if we hit the "wall" first.
180            View targetView = findViewByPosition(getTargetPosition());
181            if (hasFocus() && targetView != null) {
182                mInSelection = true;
183                targetView.requestFocus();
184                mInSelection = false;
185            }
186            if (needsDispatchChildSelectedOnStop()) {
187                dispatchChildSelected();
188            }
189            super.onStop();
190        }
191
192        boolean needsDispatchChildSelectedOnStop() {
193            return true;
194        }
195
196        @Override
197        protected void onTargetFound(View targetView,
198                RecyclerView.State state, Action action) {
199            if (getScrollPosition(targetView, sTwoInts)) {
200                int dx, dy;
201                if (mOrientation == HORIZONTAL) {
202                    dx = sTwoInts[0];
203                    dy = sTwoInts[1];
204                } else {
205                    dx = sTwoInts[1];
206                    dy = sTwoInts[0];
207                }
208                final int distance = (int) Math.sqrt(dx * dx + dy * dy);
209                final int time = calculateTimeForDeceleration(distance);
210                action.update(dx, dy, time, mDecelerateInterpolator);
211            }
212        }
213    }
214
215    /**
216     * The SmoothScroller that remembers pending DPAD keys and consume pending keys
217     * during scroll.
218     */
219    final class PendingMoveSmoothScroller extends GridLinearSmoothScroller {
220        // -2 is a target position that LinearSmoothScroller can never find until
221        // consumePendingMovesXXX() sets real targetPosition.
222        final static int TARGET_UNDEFINED = -2;
223        // whether the grid is staggered.
224        private final boolean mStaggeredGrid;
225        // Number of pending movements on primary direction, negative if PREV_ITEM.
226        private int mPendingMoves;
227
228        PendingMoveSmoothScroller(int initialPendingMoves, boolean staggeredGrid) {
229            mPendingMoves = initialPendingMoves;
230            mStaggeredGrid = staggeredGrid;
231            setTargetPosition(TARGET_UNDEFINED);
232        }
233
234        void increasePendingMoves() {
235            if (mPendingMoves < MAX_PENDING_MOVES) {
236                mPendingMoves++;
237                if (mPendingMoves == 0) {
238                    dispatchChildSelected();
239                }
240            }
241        }
242
243        void decreasePendingMoves() {
244            if (mPendingMoves > -MAX_PENDING_MOVES) {
245                mPendingMoves--;
246                if (mPendingMoves == 0) {
247                    dispatchChildSelected();
248                }
249            }
250        }
251
252        /**
253         * Called before laid out an item when non-staggered grid can handle pending movements
254         * by skipping "mNumRows" per movement;  staggered grid will have to wait the item
255         * has been laid out in consumePendingMovesAfterLayout().
256         */
257        void consumePendingMovesBeforeLayout() {
258            if (mStaggeredGrid || mPendingMoves == 0) {
259                return;
260            }
261            View newSelected = null;
262            int startPos = mPendingMoves > 0 ? mFocusPosition + mNumRows :
263                    mFocusPosition - mNumRows;
264            for (int pos = startPos; mPendingMoves != 0;
265                    pos = mPendingMoves > 0 ? pos + mNumRows: pos - mNumRows) {
266                View v = findViewByPosition(pos);
267                if (v == null) {
268                    break;
269                }
270                if (!canScrollTo(v)) {
271                    continue;
272                }
273                newSelected = v;
274                mFocusPosition = pos;
275                if (mPendingMoves > 0) {
276                    mPendingMoves--;
277                } else {
278                    mPendingMoves++;
279                }
280            }
281            if (newSelected != null && hasFocus()) {
282                mInSelection = true;
283                newSelected.requestFocus();
284                mInSelection = false;
285            }
286        }
287
288        /**
289         * Called after laid out an item.  Staggered grid should find view on same
290         * Row and consume pending movements.
291         */
292        void consumePendingMovesAfterLayout() {
293            if (mStaggeredGrid && mPendingMoves != 0) {
294                // consume pending moves, focus to item on the same row.
295                final int focusedRow = mGrid != null && mFocusPosition != NO_POSITION ?
296                        mGrid.getLocation(mFocusPosition).row : NO_POSITION;
297                View newSelected = null;
298                for (int i = 0, count = getChildCount(); i < count && mPendingMoves != 0; i++) {
299                    int index = mPendingMoves > 0 ? i : count - 1 - i;
300                    final View child = getChildAt(index);
301                    if (!canScrollTo(child)) {
302                        continue;
303                    }
304                    int position = getPositionByIndex(index);
305                    Grid.Location loc = mGrid.getLocation(position);
306                    if (focusedRow == NO_POSITION || (loc != null && loc.row == focusedRow)) {
307                        if (mFocusPosition == NO_POSITION) {
308                            mFocusPosition = position;
309                            newSelected = child;
310                        } else if ((mPendingMoves > 0 && position > mFocusPosition)
311                                || (mPendingMoves < 0 && position < mFocusPosition)) {
312                            mFocusPosition = position;
313                            if (mPendingMoves > 0) {
314                                mPendingMoves--;
315                            } else {
316                                mPendingMoves++;
317                            }
318                            newSelected = child;
319                        }
320                    }
321                }
322                if (newSelected != null && hasFocus()) {
323                    mInSelection = true;
324                    newSelected.requestFocus();
325                    mInSelection = false;
326                }
327                if (mPendingMoves == 0) {
328                    dispatchChildSelected();
329                }
330            }
331            if (mPendingMoves == 0 || (mPendingMoves > 0 && hasCreatedLastItem())
332                    || (mPendingMoves < 0 && hasCreatedFirstItem())) {
333                setTargetPosition(mFocusPosition);
334                stop();
335            }
336        }
337
338        @Override
339        protected void updateActionForInterimTarget(Action action) {
340            if (mPendingMoves == 0) {
341                return;
342            }
343            super.updateActionForInterimTarget(action);
344        }
345
346        @Override
347        public PointF computeScrollVectorForPosition(int targetPosition) {
348            if (mPendingMoves == 0) {
349                return null;
350            }
351            int direction = (mReverseFlowPrimary ? mPendingMoves > 0 : mPendingMoves < 0) ?
352                    -1 : 1;
353            if (mOrientation == HORIZONTAL) {
354                return new PointF(direction, 0);
355            } else {
356                return new PointF(0, direction);
357            }
358        }
359
360        @Override
361        boolean needsDispatchChildSelectedOnStop() {
362            return mPendingMoves != 0;
363        }
364
365        @Override
366        protected void onStop() {
367            super.onStop();
368            // if we hit wall,  need clear the remaining pending moves.
369            mPendingMoves = 0;
370            mPendingMoveSmoothScroller = null;
371            View v = findViewByPosition(getTargetPosition());
372            if (v != null) scrollToView(v, true);
373        }
374    };
375
376    private static final String TAG = "GridLayoutManager";
377    private static final boolean DEBUG = false;
378    private static final boolean TRACE = false;
379
380    // maximum pending movement in one direction.
381    private final static int MAX_PENDING_MOVES = 10;
382
383    private String getTag() {
384        return TAG + ":" + mBaseGridView.getId();
385    }
386
387    private final BaseGridView mBaseGridView;
388
389    /**
390     * Note on conventions in the presence of RTL layout directions:
391     * Many properties and method names reference entities related to the
392     * beginnings and ends of things.  In the presence of RTL flows,
393     * it may not be clear whether this is intended to reference a
394     * quantity that changes direction in RTL cases, or a quantity that
395     * does not.  Here are the conventions in use:
396     *
397     * start/end: coordinate quantities - do reverse
398     * (optical) left/right: coordinate quantities - do not reverse
399     * low/high: coordinate quantities - do not reverse
400     * min/max: coordinate quantities - do not reverse
401     * scroll offset - coordinate quantities - do not reverse
402     * first/last: positional indices - do not reverse
403     * front/end: positional indices - do not reverse
404     * prepend/append: related to positional indices - do not reverse
405     *
406     * Note that although quantities do not reverse in RTL flows, their
407     * relationship does.  In LTR flows, the first positional index is
408     * leftmost; in RTL flows, it is rightmost.  Thus, anywhere that
409     * positional quantities are mapped onto coordinate quantities,
410     * the flow must be checked and the logic reversed.
411     */
412
413    /**
414     * The orientation of a "row".
415     */
416    private int mOrientation = HORIZONTAL;
417
418    private RecyclerView.State mState;
419    private RecyclerView.Recycler mRecycler;
420
421    private boolean mInLayout;
422    private boolean mInScroll;
423    private boolean mInFastRelayout;
424    /**
425     * During full layout pass, when GridView had focus: onLayoutChildren will
426     * skip non-focusable child and adjust mFocusPosition.
427     */
428    private boolean mInLayoutSearchFocus;
429    private boolean mInSelection = false;
430
431    private OnChildSelectedListener mChildSelectedListener = null;
432
433    private OnChildLaidOutListener mChildLaidOutListener = null;
434
435    /**
436     * The focused position, it's not the currently visually aligned position
437     * but it is the final position that we intend to focus on. If there are
438     * multiple setSelection() called, mFocusPosition saves last value.
439     */
440    private int mFocusPosition = NO_POSITION;
441
442    /**
443     * LinearSmoothScroller that consume pending DPAD movements.
444     */
445    private PendingMoveSmoothScroller mPendingMoveSmoothScroller;
446
447    /**
448     * The offset to be applied to mFocusPosition, due to adapter change, on the next
449     * layout.  Set to Integer.MIN_VALUE means item was removed.
450     * TODO:  This is somewhat duplication of RecyclerView getOldPosition() which is
451     * unfortunately cleared after prelayout.
452     */
453    private int mFocusPositionOffset = 0;
454
455    /**
456     * Extra pixels applied on primary direction.
457     */
458    private int mPrimaryScrollExtra;
459
460    /**
461     * Force a full layout under certain situations.  E.g. Rows change, jump to invisible child.
462     */
463    private boolean mForceFullLayout;
464
465    /**
466     * True if layout is enabled.
467     */
468    private boolean mLayoutEnabled = true;
469
470    /**
471     * override child visibility
472     */
473    private int mChildVisibility = -1;
474
475    /**
476     * The scroll offsets of the viewport relative to the entire view.
477     */
478    private int mScrollOffsetPrimary;
479    private int mScrollOffsetSecondary;
480
481    /**
482     * User-specified row height/column width.  Can be WRAP_CONTENT.
483     */
484    private int mRowSizeSecondaryRequested;
485
486    /**
487     * The fixed size of each grid item in the secondary direction. This corresponds to
488     * the row height, equal for all rows. Grid items may have variable length
489     * in the primary direction.
490     */
491    private int mFixedRowSizeSecondary;
492
493    /**
494     * Tracks the secondary size of each row.
495     */
496    private int[] mRowSizeSecondary;
497
498    /**
499     * Flag controlling whether the current/next layout should
500     * be updating the secondary size of rows.
501     */
502    private boolean mRowSecondarySizeRefresh;
503
504    /**
505     * The maximum measured size of the view.
506     */
507    private int mMaxSizeSecondary;
508
509    /**
510     * Margin between items.
511     */
512    private int mHorizontalMargin;
513    /**
514     * Margin between items vertically.
515     */
516    private int mVerticalMargin;
517    /**
518     * Margin in main direction.
519     */
520    private int mMarginPrimary;
521    /**
522     * Margin in second direction.
523     */
524    private int mMarginSecondary;
525    /**
526     * How to position child in secondary direction.
527     */
528    private int mGravity = Gravity.START | Gravity.TOP;
529    /**
530     * The number of rows in the grid.
531     */
532    private int mNumRows;
533    /**
534     * Number of rows requested, can be 0 to be determined by parent size and
535     * rowHeight.
536     */
537    private int mNumRowsRequested = 1;
538
539    /**
540     * Saves grid information of each view.
541     */
542    Grid mGrid;
543
544    /**
545     * Focus Scroll strategy.
546     */
547    private int mFocusScrollStrategy = BaseGridView.FOCUS_SCROLL_ALIGNED;
548    /**
549     * Defines how item view is aligned in the window.
550     */
551    private final WindowAlignment mWindowAlignment = new WindowAlignment();
552
553    /**
554     * Defines how item view is aligned.
555     */
556    private final ItemAlignment mItemAlignment = new ItemAlignment();
557
558    /**
559     * Dimensions of the view, width or height depending on orientation.
560     */
561    private int mSizePrimary;
562
563    /**
564     *  Allow DPAD key to navigate out at the front of the View (where position = 0),
565     *  default is false.
566     */
567    private boolean mFocusOutFront;
568
569    /**
570     * Allow DPAD key to navigate out at the end of the view, default is false.
571     */
572    private boolean mFocusOutEnd;
573
574    /**
575     * True if focus search is disabled.
576     */
577    private boolean mFocusSearchDisabled;
578
579    /**
580     * True if prune child,  might be disabled during transition.
581     */
582    private boolean mPruneChild = true;
583
584    /**
585     * True if scroll content,  might be disabled during transition.
586     */
587    private boolean mScrollEnabled = true;
588
589    /**
590     * Temporary variable: an int array of length=2.
591     */
592    private static int[] sTwoInts = new int[2];
593
594    /**
595     * Set to true for RTL layout in horizontal orientation
596     */
597    private boolean mReverseFlowPrimary = false;
598
599    /**
600     * Set to true for RTL layout in vertical orientation
601     */
602    private boolean mReverseFlowSecondary = false;
603
604    /**
605     * Temporaries used for measuring.
606     */
607    private int[] mMeasuredDimension = new int[2];
608
609    final ViewsStateBundle mChildrenStates = new ViewsStateBundle();
610
611    public GridLayoutManager(BaseGridView baseGridView) {
612        mBaseGridView = baseGridView;
613    }
614
615    public void setOrientation(int orientation) {
616        if (orientation != HORIZONTAL && orientation != VERTICAL) {
617            if (DEBUG) Log.v(getTag(), "invalid orientation: " + orientation);
618            return;
619        }
620
621        mOrientation = orientation;
622        mWindowAlignment.setOrientation(orientation);
623        mItemAlignment.setOrientation(orientation);
624        mForceFullLayout = true;
625    }
626
627    public void onRtlPropertiesChanged(int layoutDirection) {
628        if (mOrientation == HORIZONTAL) {
629            mReverseFlowPrimary = layoutDirection == View.LAYOUT_DIRECTION_RTL;
630            mReverseFlowSecondary = false;
631        } else {
632            mReverseFlowSecondary = layoutDirection == View.LAYOUT_DIRECTION_RTL;
633            mReverseFlowPrimary = false;
634        }
635        mWindowAlignment.horizontal.setReversedFlow(layoutDirection == View.LAYOUT_DIRECTION_RTL);
636    }
637
638    public int getFocusScrollStrategy() {
639        return mFocusScrollStrategy;
640    }
641
642    public void setFocusScrollStrategy(int focusScrollStrategy) {
643        mFocusScrollStrategy = focusScrollStrategy;
644    }
645
646    public void setWindowAlignment(int windowAlignment) {
647        mWindowAlignment.mainAxis().setWindowAlignment(windowAlignment);
648    }
649
650    public int getWindowAlignment() {
651        return mWindowAlignment.mainAxis().getWindowAlignment();
652    }
653
654    public void setWindowAlignmentOffset(int alignmentOffset) {
655        mWindowAlignment.mainAxis().setWindowAlignmentOffset(alignmentOffset);
656    }
657
658    public int getWindowAlignmentOffset() {
659        return mWindowAlignment.mainAxis().getWindowAlignmentOffset();
660    }
661
662    public void setWindowAlignmentOffsetPercent(float offsetPercent) {
663        mWindowAlignment.mainAxis().setWindowAlignmentOffsetPercent(offsetPercent);
664    }
665
666    public float getWindowAlignmentOffsetPercent() {
667        return mWindowAlignment.mainAxis().getWindowAlignmentOffsetPercent();
668    }
669
670    public void setItemAlignmentOffset(int alignmentOffset) {
671        mItemAlignment.mainAxis().setItemAlignmentOffset(alignmentOffset);
672        updateChildAlignments();
673    }
674
675    public int getItemAlignmentOffset() {
676        return mItemAlignment.mainAxis().getItemAlignmentOffset();
677    }
678
679    public void setItemAlignmentOffsetWithPadding(boolean withPadding) {
680        mItemAlignment.mainAxis().setItemAlignmentOffsetWithPadding(withPadding);
681        updateChildAlignments();
682    }
683
684    public boolean isItemAlignmentOffsetWithPadding() {
685        return mItemAlignment.mainAxis().isItemAlignmentOffsetWithPadding();
686    }
687
688    public void setItemAlignmentOffsetPercent(float offsetPercent) {
689        mItemAlignment.mainAxis().setItemAlignmentOffsetPercent(offsetPercent);
690        updateChildAlignments();
691    }
692
693    public float getItemAlignmentOffsetPercent() {
694        return mItemAlignment.mainAxis().getItemAlignmentOffsetPercent();
695    }
696
697    public void setItemAlignmentViewId(int viewId) {
698        mItemAlignment.mainAxis().setItemAlignmentViewId(viewId);
699        updateChildAlignments();
700    }
701
702    public int getItemAlignmentViewId() {
703        return mItemAlignment.mainAxis().getItemAlignmentViewId();
704    }
705
706    public void setFocusOutAllowed(boolean throughFront, boolean throughEnd) {
707        mFocusOutFront = throughFront;
708        mFocusOutEnd = throughEnd;
709    }
710
711    public void setNumRows(int numRows) {
712        if (numRows < 0) throw new IllegalArgumentException();
713        mNumRowsRequested = numRows;
714        mForceFullLayout = true;
715    }
716
717    /**
718     * Set the row height. May be WRAP_CONTENT, or a size in pixels.
719     */
720    public void setRowHeight(int height) {
721        if (height >= 0 || height == ViewGroup.LayoutParams.WRAP_CONTENT) {
722            mRowSizeSecondaryRequested = height;
723        } else {
724            throw new IllegalArgumentException("Invalid row height: " + height);
725        }
726    }
727
728    public void setItemMargin(int margin) {
729        mVerticalMargin = mHorizontalMargin = margin;
730        mMarginPrimary = mMarginSecondary = margin;
731    }
732
733    public void setVerticalMargin(int margin) {
734        if (mOrientation == HORIZONTAL) {
735            mMarginSecondary = mVerticalMargin = margin;
736        } else {
737            mMarginPrimary = mVerticalMargin = margin;
738        }
739    }
740
741    public void setHorizontalMargin(int margin) {
742        if (mOrientation == HORIZONTAL) {
743            mMarginPrimary = mHorizontalMargin = margin;
744        } else {
745            mMarginSecondary = mHorizontalMargin = margin;
746        }
747    }
748
749    public int getVerticalMargin() {
750        return mVerticalMargin;
751    }
752
753    public int getHorizontalMargin() {
754        return mHorizontalMargin;
755    }
756
757    public void setGravity(int gravity) {
758        mGravity = gravity;
759    }
760
761    protected boolean hasDoneFirstLayout() {
762        return mGrid != null;
763    }
764
765    public void setOnChildSelectedListener(OnChildSelectedListener listener) {
766        mChildSelectedListener = listener;
767    }
768
769    void setOnChildLaidOutListener(OnChildLaidOutListener listener) {
770        mChildLaidOutListener = listener;
771    }
772
773    private int getPositionByView(View view) {
774        if (view == null) {
775            return NO_POSITION;
776        }
777        LayoutParams params = (LayoutParams) view.getLayoutParams();
778        if (params == null || params.isItemRemoved()) {
779            // when item is removed, the position value can be any value.
780            return NO_POSITION;
781        }
782        return params.getViewPosition();
783    }
784
785    private int getPositionByIndex(int index) {
786        return getPositionByView(getChildAt(index));
787    }
788
789    private void dispatchChildSelected() {
790        if (mChildSelectedListener == null) {
791            return;
792        }
793
794        if (TRACE) TraceHelper.beginSection("onChildSelected");
795        View view = mFocusPosition == NO_POSITION ? null : findViewByPosition(mFocusPosition);
796        if (view != null) {
797            RecyclerView.ViewHolder vh = mBaseGridView.getChildViewHolder(view);
798            mChildSelectedListener.onChildSelected(mBaseGridView, view, mFocusPosition,
799                    vh == null? NO_ID: vh.getItemId());
800        } else {
801            mChildSelectedListener.onChildSelected(mBaseGridView, null, NO_POSITION, NO_ID);
802        }
803        if (TRACE) TraceHelper.endSection();
804
805        // Children may request layout when a child selection event occurs (such as a change of
806        // padding on the current and previously selected rows).
807        // If in layout, a child requesting layout may have been laid out before the selection
808        // callback.
809        // If it was not, the child will be laid out after the selection callback.
810        // If so, the layout request will be honoured though the view system will emit a double-
811        // layout warning.
812        // If not in layout, we may be scrolling in which case the child layout request will be
813        // eaten by recyclerview.  Post a requestLayout.
814        if (!mInLayout && !mBaseGridView.isLayoutRequested()) {
815            int childCount = getChildCount();
816            for (int i = 0; i < childCount; i++) {
817                if (getChildAt(i).isLayoutRequested()) {
818                    forceRequestLayout();
819                    break;
820                }
821            }
822        }
823    }
824
825    @Override
826    public boolean canScrollHorizontally() {
827        // We can scroll horizontally if we have horizontal orientation, or if
828        // we are vertical and have more than one column.
829        return mOrientation == HORIZONTAL || mNumRows > 1;
830    }
831
832    @Override
833    public boolean canScrollVertically() {
834        // We can scroll vertically if we have vertical orientation, or if we
835        // are horizontal and have more than one row.
836        return mOrientation == VERTICAL || mNumRows > 1;
837    }
838
839    @Override
840    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
841        return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
842                ViewGroup.LayoutParams.WRAP_CONTENT);
843    }
844
845    @Override
846    public RecyclerView.LayoutParams generateLayoutParams(Context context, AttributeSet attrs) {
847        return new LayoutParams(context, attrs);
848    }
849
850    @Override
851    public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
852        if (lp instanceof LayoutParams) {
853            return new LayoutParams((LayoutParams) lp);
854        } else if (lp instanceof RecyclerView.LayoutParams) {
855            return new LayoutParams((RecyclerView.LayoutParams) lp);
856        } else if (lp instanceof MarginLayoutParams) {
857            return new LayoutParams((MarginLayoutParams) lp);
858        } else {
859            return new LayoutParams(lp);
860        }
861    }
862
863    protected View getViewForPosition(int position) {
864        return mRecycler.getViewForPosition(position);
865    }
866
867    final int getOpticalLeft(View v) {
868        return ((LayoutParams) v.getLayoutParams()).getOpticalLeft(v);
869    }
870
871    final int getOpticalRight(View v) {
872        return ((LayoutParams) v.getLayoutParams()).getOpticalRight(v);
873    }
874
875    final int getOpticalTop(View v) {
876        return ((LayoutParams) v.getLayoutParams()).getOpticalTop(v);
877    }
878
879    final int getOpticalBottom(View v) {
880        return ((LayoutParams) v.getLayoutParams()).getOpticalBottom(v);
881    }
882
883    private int getViewMin(View v) {
884        return (mOrientation == HORIZONTAL) ? getOpticalLeft(v) : getOpticalTop(v);
885    }
886
887    private int getViewMax(View v) {
888        return (mOrientation == HORIZONTAL) ? getOpticalRight(v) : getOpticalBottom(v);
889    }
890
891    private int getViewCenter(View view) {
892        return (mOrientation == HORIZONTAL) ? getViewCenterX(view) : getViewCenterY(view);
893    }
894
895    private int getViewCenterSecondary(View view) {
896        return (mOrientation == HORIZONTAL) ? getViewCenterY(view) : getViewCenterX(view);
897    }
898
899    private int getViewCenterX(View v) {
900        LayoutParams p = (LayoutParams) v.getLayoutParams();
901        return p.getOpticalLeft(v) + p.getAlignX();
902    }
903
904    private int getViewCenterY(View v) {
905        LayoutParams p = (LayoutParams) v.getLayoutParams();
906        return p.getOpticalTop(v) + p.getAlignY();
907    }
908
909    /**
910     * Save Recycler and State for convenience.  Must be paired with leaveContext().
911     */
912    private void saveContext(Recycler recycler, State state) {
913        if (mRecycler != null || mState != null) {
914            Log.e(TAG, "Recycler information was not released, bug!");
915        }
916        mRecycler = recycler;
917        mState = state;
918    }
919
920    /**
921     * Discard saved Recycler and State.
922     */
923    private void leaveContext() {
924        mRecycler = null;
925        mState = null;
926    }
927
928    /**
929     * Re-initialize data structures for a data change or handling invisible
930     * selection. The method tries its best to preserve position information so
931     * that staggered grid looks same before and after re-initialize.
932     * @return true if can fastRelayout()
933     */
934    private boolean layoutInit() {
935        boolean focusViewWasInTree = mGrid != null && mFocusPosition >= 0
936                && mFocusPosition >= mGrid.getFirstVisibleIndex()
937                && mFocusPosition <= mGrid.getLastVisibleIndex();
938        final int newItemCount = mState.getItemCount();
939        if (newItemCount == 0) {
940            mFocusPosition = NO_POSITION;
941        } else if (mFocusPosition >= newItemCount) {
942            mFocusPosition = newItemCount - 1;
943        } else if (mFocusPosition == NO_POSITION && newItemCount > 0) {
944            // if focus position is never set before,  initialize it to 0
945            mFocusPosition = 0;
946        }
947        if (!mState.didStructureChange() && mGrid.getFirstVisibleIndex() >= 0 &&
948                !mForceFullLayout && mGrid != null) {
949            updateScrollController();
950            updateScrollSecondAxis();
951            mGrid.setMargin(mMarginPrimary);
952            if (!focusViewWasInTree && mFocusPosition != NO_POSITION) {
953                mGrid.setStart(mFocusPosition);
954            }
955            return true;
956        } else {
957            mForceFullLayout = false;
958            int firstVisibleIndex = focusViewWasInTree ? mGrid.getFirstVisibleIndex() : 0;
959
960            if (mGrid == null || mNumRows != mGrid.getNumRows() ||
961                    mReverseFlowPrimary != mGrid.isReversedFlow()) {
962                mGrid = Grid.createStaggeredMultipleRows(mNumRows);
963                mGrid.setProvider(mGridProvider);
964                mGrid.setReversedFlow(mReverseFlowPrimary);
965            }
966            initScrollController();
967            updateScrollSecondAxis();
968            mGrid.setMargin(mMarginPrimary);
969            detachAndScrapAttachedViews(mRecycler);
970            mGrid.resetVisibleIndex();
971            if (mFocusPosition == NO_POSITION) {
972                mBaseGridView.clearFocus();
973            }
974            mWindowAlignment.mainAxis().invalidateScrollMin();
975            mWindowAlignment.mainAxis().invalidateScrollMax();
976            if (focusViewWasInTree && firstVisibleIndex <= mFocusPosition) {
977                // if focusView was in tree, we will add item from first visible item
978                mGrid.setStart(firstVisibleIndex);
979            } else {
980                // if focusView was not in tree, it's probably because focus position jumped
981                // far away from visible range,  so use mFocusPosition as start
982                mGrid.setStart(mFocusPosition);
983            }
984            return false;
985        }
986    }
987
988    private int getRowSizeSecondary(int rowIndex) {
989        if (mFixedRowSizeSecondary != 0) {
990            return mFixedRowSizeSecondary;
991        }
992        if (mRowSizeSecondary == null) {
993            return 0;
994        }
995        return mRowSizeSecondary[rowIndex];
996    }
997
998    private int getRowStartSecondary(int rowIndex) {
999        int start = 0;
1000        // Iterate from left to right, which is a different index traversal
1001        // in RTL flow
1002        if (mReverseFlowSecondary) {
1003            for (int i = mNumRows-1; i > rowIndex; i--) {
1004                start += getRowSizeSecondary(i) + mMarginSecondary;
1005            }
1006        } else {
1007            for (int i = 0; i < rowIndex; i++) {
1008                start += getRowSizeSecondary(i) + mMarginSecondary;
1009            }
1010        }
1011        return start;
1012    }
1013
1014    private int getSizeSecondary() {
1015        int rightmostIndex = mReverseFlowSecondary ? 0 : mNumRows - 1;
1016        return getRowStartSecondary(rightmostIndex) + getRowSizeSecondary(rightmostIndex);
1017    }
1018
1019    private void measureScrapChild(int position, int widthSpec, int heightSpec,
1020            int[] measuredDimension) {
1021        View view = mRecycler.getViewForPosition(position);
1022        if (view != null) {
1023            LayoutParams p = (LayoutParams) view.getLayoutParams();
1024            int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
1025                    getPaddingLeft() + getPaddingRight(), p.width);
1026            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
1027                    getPaddingTop() + getPaddingBottom(), p.height);
1028            view.measure(childWidthSpec, childHeightSpec);
1029            measuredDimension[0] = view.getMeasuredWidth();
1030            measuredDimension[1] = view.getMeasuredHeight();
1031            mRecycler.recycleView(view);
1032        }
1033    }
1034
1035    private boolean processRowSizeSecondary(boolean measure) {
1036        if (mFixedRowSizeSecondary != 0) {
1037            return false;
1038        }
1039
1040        if (TRACE) TraceHelper.beginSection("processRowSizeSecondary");
1041        CircularIntArray[] rows = mGrid == null ? null : mGrid.getItemPositionsInRows();
1042        boolean changed = false;
1043        int scrapChildWidth = -1;
1044        int scrapChildHeight = -1;
1045
1046        for (int rowIndex = 0; rowIndex < mNumRows; rowIndex++) {
1047            CircularIntArray row = rows == null ? null : rows[rowIndex];
1048            final int rowItemsPairCount = row == null ? 0 : row.size();
1049            int rowSize = -1;
1050            for (int rowItemPairIndex = 0; rowItemPairIndex < rowItemsPairCount;
1051                    rowItemPairIndex += 2) {
1052                final int rowIndexStart = row.get(rowItemPairIndex);
1053                final int rowIndexEnd = row.get(rowItemPairIndex + 1);
1054                for (int i = rowIndexStart; i <= rowIndexEnd; i++) {
1055                    final View view = findViewByPosition(i);
1056                    if (view == null) {
1057                        continue;
1058                    }
1059                    if (measure && view.isLayoutRequested()) {
1060                        measureChild(view);
1061                    }
1062                    final int secondarySize = mOrientation == HORIZONTAL ?
1063                            view.getMeasuredHeight() : view.getMeasuredWidth();
1064                    if (secondarySize > rowSize) {
1065                        rowSize = secondarySize;
1066                    }
1067                }
1068            }
1069
1070            final int itemCount = mState.getItemCount();
1071            if (measure && rowSize < 0 && itemCount > 0) {
1072                if (scrapChildWidth < 0 && scrapChildHeight < 0) {
1073                    int position;
1074                    if (mFocusPosition == NO_POSITION) {
1075                        position = 0;
1076                    } else if (mFocusPosition >= itemCount) {
1077                        position = itemCount - 1;
1078                    } else {
1079                        position = mFocusPosition;
1080                    }
1081                    measureScrapChild(position,
1082                            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
1083                            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
1084                            mMeasuredDimension);
1085                    scrapChildWidth = mMeasuredDimension[0];
1086                    scrapChildHeight = mMeasuredDimension[1];
1087                    if (DEBUG) Log.v(TAG, "measured scrap child: " + scrapChildWidth +
1088                            " " + scrapChildHeight);
1089                }
1090                rowSize = mOrientation == HORIZONTAL ? scrapChildHeight : scrapChildWidth;
1091            }
1092            if (rowSize < 0) {
1093                rowSize = 0;
1094            }
1095            if (mRowSizeSecondary[rowIndex] != rowSize) {
1096                if (DEBUG) Log.v(getTag(), "row size secondary changed: " + mRowSizeSecondary[rowIndex] +
1097                        ", " + rowSize);
1098                mRowSizeSecondary[rowIndex] = rowSize;
1099                changed = true;
1100            }
1101        }
1102
1103        if (TRACE) TraceHelper.endSection();
1104        return changed;
1105    }
1106
1107    /**
1108     * Checks if we need to update row secondary sizes.
1109     */
1110    private void updateRowSecondarySizeRefresh() {
1111        mRowSecondarySizeRefresh = processRowSizeSecondary(false);
1112        if (mRowSecondarySizeRefresh) {
1113            if (DEBUG) Log.v(getTag(), "mRowSecondarySizeRefresh now set");
1114            forceRequestLayout();
1115        }
1116    }
1117
1118    private void forceRequestLayout() {
1119        if (DEBUG) Log.v(getTag(), "forceRequestLayout");
1120        // RecyclerView prevents us from requesting layout in many cases
1121        // (during layout, during scroll, etc.)
1122        // For secondary row size wrap_content support we currently need a
1123        // second layout pass to update the measured size after having measured
1124        // and added child views in layoutChildren.
1125        // Force the second layout by posting a delayed runnable.
1126        // TODO: investigate allowing a second layout pass,
1127        // or move child add/measure logic to the measure phase.
1128        ViewCompat.postOnAnimation(mBaseGridView, mRequestLayoutRunnable);
1129    }
1130
1131    private final Runnable mRequestLayoutRunnable = new Runnable() {
1132        @Override
1133        public void run() {
1134            if (DEBUG) Log.v(getTag(), "request Layout from runnable");
1135            requestLayout();
1136        }
1137     };
1138
1139    @Override
1140    public void onMeasure(Recycler recycler, State state, int widthSpec, int heightSpec) {
1141        saveContext(recycler, state);
1142
1143        int sizePrimary, sizeSecondary, modeSecondary, paddingSecondary;
1144        int measuredSizeSecondary;
1145        if (mOrientation == HORIZONTAL) {
1146            sizePrimary = MeasureSpec.getSize(widthSpec);
1147            sizeSecondary = MeasureSpec.getSize(heightSpec);
1148            modeSecondary = MeasureSpec.getMode(heightSpec);
1149            paddingSecondary = getPaddingTop() + getPaddingBottom();
1150        } else {
1151            sizeSecondary = MeasureSpec.getSize(widthSpec);
1152            sizePrimary = MeasureSpec.getSize(heightSpec);
1153            modeSecondary = MeasureSpec.getMode(widthSpec);
1154            paddingSecondary = getPaddingLeft() + getPaddingRight();
1155        }
1156        if (DEBUG) Log.v(getTag(), "onMeasure widthSpec " + Integer.toHexString(widthSpec) +
1157                " heightSpec " + Integer.toHexString(heightSpec) +
1158                " modeSecondary " + Integer.toHexString(modeSecondary) +
1159                " sizeSecondary " + sizeSecondary + " " + this);
1160
1161        mMaxSizeSecondary = sizeSecondary;
1162
1163        if (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) {
1164            mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested;
1165            mFixedRowSizeSecondary = 0;
1166
1167            if (mRowSizeSecondary == null || mRowSizeSecondary.length != mNumRows) {
1168                mRowSizeSecondary = new int[mNumRows];
1169            }
1170
1171            // Measure all current children and update cached row heights
1172            processRowSizeSecondary(true);
1173
1174            switch (modeSecondary) {
1175            case MeasureSpec.UNSPECIFIED:
1176                measuredSizeSecondary = getSizeSecondary() + paddingSecondary;
1177                break;
1178            case MeasureSpec.AT_MOST:
1179                measuredSizeSecondary = Math.min(getSizeSecondary() + paddingSecondary,
1180                        mMaxSizeSecondary);
1181                break;
1182            case MeasureSpec.EXACTLY:
1183                measuredSizeSecondary = mMaxSizeSecondary;
1184                break;
1185            default:
1186                throw new IllegalStateException("wrong spec");
1187            }
1188
1189        } else {
1190            switch (modeSecondary) {
1191            case MeasureSpec.UNSPECIFIED:
1192                if (mRowSizeSecondaryRequested == 0) {
1193                    if (mOrientation == HORIZONTAL) {
1194                        throw new IllegalStateException("Must specify rowHeight or view height");
1195                    } else {
1196                        throw new IllegalStateException("Must specify columnWidth or view width");
1197                    }
1198                }
1199                mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
1200                mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested;
1201                measuredSizeSecondary = mFixedRowSizeSecondary * mNumRows + mMarginSecondary
1202                    * (mNumRows - 1) + paddingSecondary;
1203                break;
1204            case MeasureSpec.AT_MOST:
1205            case MeasureSpec.EXACTLY:
1206                if (mNumRowsRequested == 0 && mRowSizeSecondaryRequested == 0) {
1207                    mNumRows = 1;
1208                    mFixedRowSizeSecondary = sizeSecondary - paddingSecondary;
1209                } else if (mNumRowsRequested == 0) {
1210                    mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
1211                    mNumRows = (sizeSecondary + mMarginSecondary)
1212                        / (mRowSizeSecondaryRequested + mMarginSecondary);
1213                } else if (mRowSizeSecondaryRequested == 0) {
1214                    mNumRows = mNumRowsRequested;
1215                    mFixedRowSizeSecondary = (sizeSecondary - paddingSecondary - mMarginSecondary
1216                            * (mNumRows - 1)) / mNumRows;
1217                } else {
1218                    mNumRows = mNumRowsRequested;
1219                    mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
1220                }
1221                measuredSizeSecondary = sizeSecondary;
1222                if (modeSecondary == MeasureSpec.AT_MOST) {
1223                    int childrenSize = mFixedRowSizeSecondary * mNumRows + mMarginSecondary
1224                        * (mNumRows - 1) + paddingSecondary;
1225                    if (childrenSize < measuredSizeSecondary) {
1226                        measuredSizeSecondary = childrenSize;
1227                    }
1228                }
1229                break;
1230            default:
1231                throw new IllegalStateException("wrong spec");
1232            }
1233        }
1234        if (mOrientation == HORIZONTAL) {
1235            setMeasuredDimension(sizePrimary, measuredSizeSecondary);
1236        } else {
1237            setMeasuredDimension(measuredSizeSecondary, sizePrimary);
1238        }
1239        if (DEBUG) {
1240            Log.v(getTag(), "onMeasure sizePrimary " + sizePrimary +
1241                    " measuredSizeSecondary " + measuredSizeSecondary +
1242                    " mFixedRowSizeSecondary " + mFixedRowSizeSecondary +
1243                    " mNumRows " + mNumRows);
1244        }
1245        leaveContext();
1246    }
1247
1248    private void measureChild(View child) {
1249        if (TRACE) TraceHelper.beginSection("measureChild");
1250        final ViewGroup.LayoutParams lp = child.getLayoutParams();
1251        final int secondarySpec = (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) ?
1252                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) :
1253                MeasureSpec.makeMeasureSpec(mFixedRowSizeSecondary, MeasureSpec.EXACTLY);
1254        int widthSpec, heightSpec;
1255
1256        if (mOrientation == HORIZONTAL) {
1257            widthSpec = ViewGroup.getChildMeasureSpec(
1258                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
1259                    0, lp.width);
1260            heightSpec = ViewGroup.getChildMeasureSpec(secondarySpec, 0, lp.height);
1261        } else {
1262            heightSpec = ViewGroup.getChildMeasureSpec(
1263                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
1264                    0, lp.height);
1265            widthSpec = ViewGroup.getChildMeasureSpec(secondarySpec, 0, lp.width);
1266        }
1267        child.measure(widthSpec, heightSpec);
1268        if (DEBUG) Log.v(getTag(), "measureChild secondarySpec " + Integer.toHexString(secondarySpec) +
1269                " widthSpec " + Integer.toHexString(widthSpec) +
1270                " heightSpec " + Integer.toHexString(heightSpec) +
1271                " measuredWidth " + child.getMeasuredWidth() +
1272                " measuredHeight " + child.getMeasuredHeight());
1273        if (DEBUG) Log.v(getTag(), "child lp width " + lp.width + " height " + lp.height);
1274        if (TRACE) TraceHelper.endSection();
1275    }
1276
1277    private Grid.Provider mGridProvider = new Grid.Provider() {
1278
1279        @Override
1280        public int getCount() {
1281            return mState.getItemCount();
1282        }
1283
1284        @Override
1285        public int createItem(int index, boolean append, Object[] item) {
1286            if (TRACE) TraceHelper.beginSection("createItem");
1287            if (TRACE) TraceHelper.beginSection("getview");
1288            View v = getViewForPosition(index);
1289            if (TRACE) TraceHelper.endSection();
1290            // See recyclerView docs:  we don't need re-add scraped view if it was removed.
1291            if (!((RecyclerView.LayoutParams) v.getLayoutParams()).isItemRemoved()) {
1292                if (TRACE) TraceHelper.beginSection("addView");
1293                if (append) {
1294                    addView(v);
1295                } else {
1296                    addView(v, 0);
1297                }
1298                if (TRACE) TraceHelper.endSection();
1299                if (mChildVisibility != -1) {
1300                    v.setVisibility(mChildVisibility);
1301                }
1302
1303                if (mPendingMoveSmoothScroller != null) {
1304                    mPendingMoveSmoothScroller.consumePendingMovesBeforeLayout();
1305                }
1306                if (!mInLayout) {
1307                    // when we are appending item during scroll pass and the item's position
1308                    // matches the mFocusPosition,  we should signal a childSelected event.
1309                    // However if we are still running PendingMoveSmoothScroller,  we defer and
1310                    // signal the event in PendingMoveSmoothScroller.onStop().  This can
1311                    // avoid lots of childSelected events during a long smooth scrolling and
1312                    // increase performance.
1313                    if (index == mFocusPosition && (mPendingMoveSmoothScroller == null
1314                            || mPendingMoveSmoothScroller.mPendingMoves == 0)) {
1315                        dispatchChildSelected();
1316                    }
1317                } else if (!mInFastRelayout) {
1318                    // fastRelayout will dispatch event at end of onLayoutChildren().
1319                    // For full layout, two situations here:
1320                    // 1. mInLayoutSearchFocus is false, dispatchChildSelected() at mFocusPosition.
1321                    // 2. mInLayoutSearchFocus is true:  dispatchChildSelected() on first child
1322                    //    equal to or after mFocusPosition that can take focus.
1323                    if (!mInLayoutSearchFocus && index == mFocusPosition) {
1324                        dispatchChildSelected();
1325                    } else if (mInLayoutSearchFocus && index >= mFocusPosition
1326                            && v.hasFocusable()) {
1327                        mFocusPosition = index;
1328                        mInLayoutSearchFocus = false;
1329                        dispatchChildSelected();
1330                    }
1331                }
1332                measureChild(v);
1333            }
1334            item[0] = v;
1335            return mOrientation == HORIZONTAL ? v.getMeasuredWidth() : v.getMeasuredHeight();
1336        }
1337
1338        @Override
1339        public void addItem(Object item, int index, int length, int rowIndex, int edge) {
1340            View v = (View) item;
1341            int start, end;
1342            if (edge == Integer.MIN_VALUE || edge == Integer.MAX_VALUE) {
1343                edge = !mGrid.isReversedFlow() ? mWindowAlignment.mainAxis().getPaddingLow()
1344                        : mWindowAlignment.mainAxis().getSize()
1345                                - mWindowAlignment.mainAxis().getPaddingHigh();
1346            }
1347            boolean edgeIsMin = !mGrid.isReversedFlow();
1348            if (edgeIsMin) {
1349                start = edge;
1350                end = edge + length;
1351            } else {
1352                start = edge - length;
1353                end = edge;
1354            }
1355            int startSecondary = getRowStartSecondary(rowIndex) - mScrollOffsetSecondary;
1356            mChildrenStates.loadView(v, index);
1357            layoutChild(rowIndex, v, start, end, startSecondary);
1358            if (DEBUG) {
1359                Log.d(getTag(), "addView " + index + " " + v);
1360            }
1361            if (TRACE) TraceHelper.endSection();
1362
1363            if (index == mGrid.getFirstVisibleIndex()) {
1364                if (!mGrid.isReversedFlow()) {
1365                    updateScrollMin();
1366                } else {
1367                    updateScrollMax();
1368                }
1369            }
1370            if (index == mGrid.getLastVisibleIndex()) {
1371                if (!mGrid.isReversedFlow()) {
1372                    updateScrollMax();
1373                } else {
1374                    updateScrollMin();
1375                }
1376            }
1377            if (!mInLayout && mPendingMoveSmoothScroller != null) {
1378                mPendingMoveSmoothScroller.consumePendingMovesAfterLayout();
1379            }
1380            if (mChildLaidOutListener != null) {
1381                RecyclerView.ViewHolder vh = mBaseGridView.getChildViewHolder(v);
1382                mChildLaidOutListener.onChildLaidOut(mBaseGridView, v, index,
1383                        vh == null ? NO_ID : vh.getItemId());
1384            }
1385        }
1386
1387        @Override
1388        public void removeItem(int index) {
1389            if (TRACE) TraceHelper.beginSection("removeItem");
1390            View v = findViewByPosition(index);
1391            if (mInLayout) {
1392                detachAndScrapView(v, mRecycler);
1393            } else {
1394                removeAndRecycleView(v, mRecycler);
1395            }
1396            if (TRACE) TraceHelper.endSection();
1397        }
1398
1399        @Override
1400        public int getEdge(int index) {
1401            if (mReverseFlowPrimary) {
1402                return getViewMax(findViewByPosition(index));
1403            } else {
1404                return getViewMin(findViewByPosition(index));
1405            }
1406        }
1407
1408        @Override
1409        public int getSize(int index) {
1410            final View v = findViewByPosition(index);
1411            return mOrientation == HORIZONTAL ? v.getMeasuredWidth() : v.getMeasuredHeight();
1412        }
1413    };
1414
1415    private void layoutChild(int rowIndex, View v, int start, int end, int startSecondary) {
1416        if (TRACE) TraceHelper.beginSection("layoutChild");
1417        int sizeSecondary = mOrientation == HORIZONTAL ? v.getMeasuredHeight()
1418                : v.getMeasuredWidth();
1419        if (mFixedRowSizeSecondary > 0) {
1420            sizeSecondary = Math.min(sizeSecondary, mFixedRowSizeSecondary);
1421        }
1422        final int verticalGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
1423        final int horizontalGravity = (mReverseFlowPrimary || mReverseFlowSecondary) ?
1424                Gravity.getAbsoluteGravity(mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK, View.LAYOUT_DIRECTION_RTL) :
1425                mGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
1426        if (mOrientation == HORIZONTAL && verticalGravity == Gravity.TOP
1427                || mOrientation == VERTICAL && horizontalGravity == Gravity.LEFT) {
1428            // do nothing
1429        } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.BOTTOM
1430                || mOrientation == VERTICAL && horizontalGravity == Gravity.RIGHT) {
1431            startSecondary += getRowSizeSecondary(rowIndex) - sizeSecondary;
1432        } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.CENTER_VERTICAL
1433                || mOrientation == VERTICAL && horizontalGravity == Gravity.CENTER_HORIZONTAL) {
1434            startSecondary += (getRowSizeSecondary(rowIndex) - sizeSecondary) / 2;
1435        }
1436        int left, top, right, bottom;
1437        if (mOrientation == HORIZONTAL) {
1438            left = start;
1439            top = startSecondary;
1440            right = end;
1441            bottom = startSecondary + sizeSecondary;
1442        } else {
1443            top = start;
1444            left = startSecondary;
1445            bottom = end;
1446            right = startSecondary + sizeSecondary;
1447        }
1448        v.layout(left, top, right, bottom);
1449        updateChildOpticalInsets(v, left, top, right, bottom);
1450        updateChildAlignments(v);
1451        if (TRACE) TraceHelper.endSection();
1452    }
1453
1454    private void updateChildOpticalInsets(View v, int left, int top, int right, int bottom) {
1455        LayoutParams p = (LayoutParams) v.getLayoutParams();
1456        p.setOpticalInsets(left - v.getLeft(), top - v.getTop(),
1457                v.getRight() - right, v.getBottom() - bottom);
1458    }
1459
1460    private void updateChildAlignments(View v) {
1461        LayoutParams p = (LayoutParams) v.getLayoutParams();
1462        p.setAlignX(mItemAlignment.horizontal.getAlignmentPosition(v));
1463        p.setAlignY(mItemAlignment.vertical.getAlignmentPosition(v));
1464    }
1465
1466    private void updateChildAlignments() {
1467        for (int i = 0, c = getChildCount(); i < c; i++) {
1468            updateChildAlignments(getChildAt(i));
1469        }
1470    }
1471
1472    private void removeInvisibleViewsAtEnd() {
1473        if (mPruneChild) {
1474            mGrid.removeInvisibleItemsAtEnd(mFocusPosition,
1475                    mReverseFlowPrimary ? 0 : mSizePrimary);
1476        }
1477    }
1478
1479    private void removeInvisibleViewsAtFront() {
1480        if (mPruneChild) {
1481            mGrid.removeInvisibleItemsAtFront(mFocusPosition,
1482                    mReverseFlowPrimary ? mSizePrimary : 0);
1483        }
1484    }
1485
1486    private boolean appendOneColumnVisibleItems() {
1487        return mGrid.appendOneColumnVisibleItems();
1488    }
1489
1490    private boolean prependOneColumnVisibleItems() {
1491        return mGrid.prependOneColumnVisibleItems();
1492    }
1493
1494    private void appendVisibleItems() {
1495        mGrid.appendVisibleItems(mReverseFlowPrimary ? 0 : mSizePrimary);
1496    }
1497
1498    private void prependVisibleItems() {
1499        mGrid.prependVisibleItems(mReverseFlowPrimary ? mSizePrimary : 0);
1500    }
1501
1502    /**
1503     * Fast layout when there is no structure change, adapter change, etc.
1504     * It will layout all views was layout requested or updated, until hit a view
1505     * with different size,  then it break and detachAndScrap all views after that.
1506     */
1507    private void fastRelayout() {
1508        boolean invalidateAfter = false;
1509        final int childCount = getChildCount();
1510        int position = -1;
1511        for (int index = 0; index < childCount; index++) {
1512            View view = getChildAt(index);
1513            position = getPositionByIndex(index);
1514            Grid.Location location = mGrid.getLocation(position);
1515            if (location == null) {
1516                if (DEBUG) Log.w(getTag(), "fastRelayout(): no Location at " + position);
1517                invalidateAfter = true;
1518                break;
1519            }
1520
1521            int startSecondary = getRowStartSecondary(location.row) - mScrollOffsetSecondary;
1522            int primarySize, end;
1523            int start = getViewMin(view);
1524            int oldPrimarySize = (mOrientation == HORIZONTAL) ?
1525                    view.getMeasuredWidth() :
1526                    view.getMeasuredHeight();
1527
1528            LayoutParams lp = (LayoutParams) view.getLayoutParams();
1529            if (lp.viewNeedsUpdate()) {
1530                int viewIndex = mBaseGridView.indexOfChild(view);
1531                detachAndScrapView(view, mRecycler);
1532                view = getViewForPosition(position);
1533                addView(view, viewIndex);
1534            }
1535
1536            if (view.isLayoutRequested()) {
1537                measureChild(view);
1538            }
1539            if (mOrientation == HORIZONTAL) {
1540                primarySize = view.getMeasuredWidth();
1541                end = start + primarySize;
1542            } else {
1543                primarySize = view.getMeasuredHeight();
1544                end = start + primarySize;
1545            }
1546            layoutChild(location.row, view, start, end, startSecondary);
1547            if (oldPrimarySize != primarySize) {
1548                // size changed invalidate remaining Locations
1549                if (DEBUG) Log.d(getTag(), "fastRelayout: view size changed at " + position);
1550                invalidateAfter = true;
1551                break;
1552            }
1553        }
1554        if (invalidateAfter) {
1555            final int savedLastPos = mGrid.getLastVisibleIndex();
1556            mGrid.invalidateItemsAfter(position);
1557            if (mPruneChild) {
1558                // in regular prune child mode, we just append items up to edge limit
1559                appendVisibleItems();
1560                if (mFocusPosition >= 0 && mFocusPosition <= savedLastPos) {
1561                    // make sure add focus view back:  the view might be outside edge limit
1562                    // when there is delta in onLayoutChildren().
1563                    while (mGrid.getLastVisibleIndex() < mFocusPosition) {
1564                        mGrid.appendOneColumnVisibleItems();
1565                    }
1566                }
1567            } else {
1568                // prune disabled(e.g. in RowsFragment transition): append all removed items
1569                while (mGrid.appendOneColumnVisibleItems()
1570                        && mGrid.getLastVisibleIndex() < savedLastPos);
1571            }
1572        }
1573        updateScrollMin();
1574        updateScrollMax();
1575        updateScrollSecondAxis();
1576    }
1577
1578    public void removeAndRecycleAllViews(RecyclerView.Recycler recycler) {
1579        if (TRACE) TraceHelper.beginSection("removeAndRecycleAllViews");
1580        if (DEBUG) Log.v(TAG, "removeAndRecycleAllViews " + getChildCount());
1581        for (int i = getChildCount() - 1; i >= 0; i--) {
1582            removeAndRecycleViewAt(i, recycler);
1583        }
1584        if (TRACE) TraceHelper.endSection();
1585    }
1586
1587    // Lays out items based on the current scroll position
1588    @Override
1589    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
1590        if (DEBUG) {
1591            Log.v(getTag(), "layoutChildren start numRows " + mNumRows + " mScrollOffsetSecondary "
1592                    + mScrollOffsetSecondary + " mScrollOffsetPrimary " + mScrollOffsetPrimary
1593                    + " inPreLayout " + state.isPreLayout()
1594                    + " didStructureChange " + state.didStructureChange()
1595                    + " mForceFullLayout " + mForceFullLayout);
1596            Log.v(getTag(), "width " + getWidth() + " height " + getHeight());
1597        }
1598
1599        if (mNumRows == 0) {
1600            // haven't done measure yet
1601            return;
1602        }
1603        final int itemCount = state.getItemCount();
1604        if (itemCount < 0) {
1605            return;
1606        }
1607
1608        if (!mLayoutEnabled) {
1609            discardLayoutInfo();
1610            removeAndRecycleAllViews(recycler);
1611            return;
1612        }
1613        mInLayout = true;
1614
1615        final boolean scrollToFocus = !isSmoothScrolling()
1616                && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED;
1617        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
1618            mFocusPosition = mFocusPosition + mFocusPositionOffset;
1619            mFocusPositionOffset = 0;
1620        }
1621        saveContext(recycler, state);
1622
1623        // Track the old focus view so we can adjust our system scroll position
1624        // so that any scroll animations happening now will remain valid.
1625        // We must use same delta in Pre Layout (if prelayout exists) and second layout.
1626        // So we cache the deltas in PreLayout and use it in second layout.
1627        int delta = 0, deltaSecondary = 0;
1628        if (mFocusPosition != NO_POSITION && scrollToFocus
1629                && mBaseGridView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) {
1630            // FIXME: we should get the remaining scroll animation offset from RecyclerView
1631            View focusView = findViewByPosition(mFocusPosition);
1632            if (focusView != null) {
1633                delta = mWindowAlignment.mainAxis().getSystemScrollPos(mScrollOffsetPrimary
1634                        + getViewCenter(focusView), false, false) - mScrollOffsetPrimary;
1635                deltaSecondary = mWindowAlignment.secondAxis().getSystemScrollPos(
1636                        mScrollOffsetSecondary + getViewCenterSecondary(focusView),
1637                        false, false) - mScrollOffsetSecondary;
1638            }
1639        }
1640
1641        boolean hadFocus = mBaseGridView.hasFocus();
1642        int savedFocusPos = mFocusPosition;
1643        if (mInFastRelayout = layoutInit()) {
1644            fastRelayout();
1645            // appends items till focus position.
1646            if (mFocusPosition != NO_POSITION) {
1647                View focusView = findViewByPosition(mFocusPosition);
1648                if (focusView != null) {
1649                    if (scrollToFocus) {
1650                        scrollToView(focusView, false);
1651                    }
1652                    if (hadFocus) {
1653                        focusView.requestFocus();
1654                    }
1655                }
1656            }
1657        } else {
1658            mInLayoutSearchFocus = hadFocus;
1659            if (mFocusPosition != NO_POSITION) {
1660                // appends items till focus position.
1661                while (appendOneColumnVisibleItems()
1662                        && findViewByPosition(mFocusPosition) == null) ;
1663            }
1664            // multiple rounds: scrollToView of first round may drag first/last child into
1665            // "visible window" and we update scrollMin/scrollMax then run second scrollToView
1666            int oldFirstVisible;
1667            int oldLastVisible;
1668            do {
1669                updateScrollMin();
1670                updateScrollMax();
1671                oldFirstVisible = mGrid.getFirstVisibleIndex();
1672                oldLastVisible = mGrid.getLastVisibleIndex();
1673                View focusView = findViewByPosition(mFocusPosition);
1674                // we need force to initialize the child view's position
1675                scrollToView(focusView, false);
1676                if (focusView != null && hadFocus) {
1677                    focusView.requestFocus();
1678                }
1679                appendVisibleItems();
1680                prependVisibleItems();
1681                removeInvisibleViewsAtFront();
1682                removeInvisibleViewsAtEnd();
1683            } while (mGrid.getFirstVisibleIndex() != oldFirstVisible ||
1684                    mGrid.getLastVisibleIndex() != oldLastVisible);
1685        }
1686
1687        if (scrollToFocus) {
1688            scrollDirectionPrimary(-delta);
1689            scrollDirectionSecondary(-deltaSecondary);
1690        }
1691        appendVisibleItems();
1692        prependVisibleItems();
1693        removeInvisibleViewsAtFront();
1694        removeInvisibleViewsAtEnd();
1695
1696        if (DEBUG) {
1697            StringWriter sw = new StringWriter();
1698            PrintWriter pw = new PrintWriter(sw);
1699            mGrid.debugPrint(pw);
1700            Log.d(getTag(), sw.toString());
1701        }
1702
1703        if (mRowSecondarySizeRefresh) {
1704            mRowSecondarySizeRefresh = false;
1705        } else {
1706            updateRowSecondarySizeRefresh();
1707        }
1708
1709        // For fastRelayout, only dispatch event when focus position changes.
1710        if (mInFastRelayout && mFocusPosition != savedFocusPos) {
1711            dispatchChildSelected();
1712        } else if (!mInFastRelayout && mInLayoutSearchFocus) {
1713            // For full layout we dispatchChildSelected() in createItem() unless searched all
1714            // children and found none is focusable then dispatchChildSelected() here.
1715            dispatchChildSelected();
1716        }
1717
1718        mInLayout = false;
1719        leaveContext();
1720        if (DEBUG) Log.v(getTag(), "layoutChildren end");
1721    }
1722
1723    private void offsetChildrenSecondary(int increment) {
1724        final int childCount = getChildCount();
1725        if (mOrientation == HORIZONTAL) {
1726            for (int i = 0; i < childCount; i++) {
1727                getChildAt(i).offsetTopAndBottom(increment);
1728            }
1729        } else {
1730            for (int i = 0; i < childCount; i++) {
1731                getChildAt(i).offsetLeftAndRight(increment);
1732            }
1733        }
1734    }
1735
1736    private void offsetChildrenPrimary(int increment) {
1737        final int childCount = getChildCount();
1738        if (mOrientation == VERTICAL) {
1739            for (int i = 0; i < childCount; i++) {
1740                getChildAt(i).offsetTopAndBottom(increment);
1741            }
1742        } else {
1743            for (int i = 0; i < childCount; i++) {
1744                getChildAt(i).offsetLeftAndRight(increment);
1745            }
1746        }
1747    }
1748
1749    @Override
1750    public int scrollHorizontallyBy(int dx, Recycler recycler, RecyclerView.State state) {
1751        if (DEBUG) Log.v(getTag(), "scrollHorizontallyBy " + dx);
1752        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1753            return 0;
1754        }
1755        saveContext(recycler, state);
1756        mInScroll = true;
1757        int result;
1758        if (mOrientation == HORIZONTAL) {
1759            result = scrollDirectionPrimary(dx);
1760        } else {
1761            result = scrollDirectionSecondary(dx);
1762        }
1763        leaveContext();
1764        mInScroll = false;
1765        return result;
1766    }
1767
1768    @Override
1769    public int scrollVerticallyBy(int dy, Recycler recycler, RecyclerView.State state) {
1770        if (DEBUG) Log.v(getTag(), "scrollVerticallyBy " + dy);
1771        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1772            return 0;
1773        }
1774        mInScroll = true;
1775        saveContext(recycler, state);
1776        int result;
1777        if (mOrientation == VERTICAL) {
1778            result = scrollDirectionPrimary(dy);
1779        } else {
1780            result = scrollDirectionSecondary(dy);
1781        }
1782        leaveContext();
1783        mInScroll = false;
1784        return result;
1785    }
1786
1787    // scroll in main direction may add/prune views
1788    private int scrollDirectionPrimary(int da) {
1789        if (TRACE) TraceHelper.beginSection("scrollPrimary");
1790        boolean isMaxUnknown = false, isMinUnknown = false;
1791        int minScroll = 0, maxScroll = 0;
1792        if (da > 0) {
1793            isMaxUnknown = mWindowAlignment.mainAxis().isMaxUnknown();
1794            if (!isMaxUnknown) {
1795                maxScroll = mWindowAlignment.mainAxis().getMaxScroll();
1796                if (mScrollOffsetPrimary + da > maxScroll) {
1797                    da = maxScroll - mScrollOffsetPrimary;
1798                }
1799            }
1800        } else if (da < 0) {
1801            isMinUnknown = mWindowAlignment.mainAxis().isMinUnknown();
1802            if (!isMinUnknown) {
1803                minScroll = mWindowAlignment.mainAxis().getMinScroll();
1804                if (mScrollOffsetPrimary + da < minScroll) {
1805                    da = minScroll - mScrollOffsetPrimary;
1806                }
1807            }
1808        }
1809        if (da == 0) {
1810            if (TRACE) TraceHelper.endSection();
1811            return 0;
1812        }
1813        offsetChildrenPrimary(-da);
1814        mScrollOffsetPrimary += da;
1815        if (mInLayout) {
1816            if (TRACE) TraceHelper.endSection();
1817            return da;
1818        }
1819
1820        int childCount = getChildCount();
1821        boolean updated;
1822
1823        if (mReverseFlowPrimary ? da > 0 : da < 0) {
1824            prependVisibleItems();
1825        } else {
1826            appendVisibleItems();
1827        }
1828        updated = getChildCount() > childCount;
1829        childCount = getChildCount();
1830
1831        if (TRACE) TraceHelper.beginSection("remove");
1832        if (mReverseFlowPrimary ? da > 0 : da < 0) {
1833            removeInvisibleViewsAtEnd();
1834        } else {
1835            removeInvisibleViewsAtFront();
1836        }
1837        if (TRACE) TraceHelper.endSection();
1838        updated |= getChildCount() < childCount;
1839        if (updated) {
1840            updateRowSecondarySizeRefresh();
1841        }
1842
1843        mBaseGridView.invalidate();
1844        if (TRACE) TraceHelper.endSection();
1845        return da;
1846    }
1847
1848    // scroll in second direction will not add/prune views
1849    private int scrollDirectionSecondary(int dy) {
1850        if (dy == 0) {
1851            return 0;
1852        }
1853        offsetChildrenSecondary(-dy);
1854        mScrollOffsetSecondary += dy;
1855        mBaseGridView.invalidate();
1856        return dy;
1857    }
1858
1859    private void updateScrollMax() {
1860        int highVisiblePos = (!mReverseFlowPrimary) ? mGrid.getLastVisibleIndex()
1861                : mGrid.getFirstVisibleIndex();
1862        int highMaxPos = (!mReverseFlowPrimary) ? mState.getItemCount() - 1 : 0;
1863        if (highVisiblePos < 0) {
1864            return;
1865        }
1866        final boolean highAvailable = highVisiblePos == highMaxPos;
1867        final boolean maxUnknown = mWindowAlignment.mainAxis().isMaxUnknown();
1868        if (!highAvailable && maxUnknown) {
1869            return;
1870        }
1871        int maxEdge = mGrid.findRowMax(true, sTwoInts) + mScrollOffsetPrimary;
1872        int rowIndex = sTwoInts[0];
1873        int pos = sTwoInts[1];
1874        int savedMaxEdge = mWindowAlignment.mainAxis().getMaxEdge();
1875        mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1876        int maxScroll = getPrimarySystemScrollPosition(findViewByPosition(pos));
1877        mWindowAlignment.mainAxis().setMaxEdge(savedMaxEdge);
1878
1879        if (highAvailable) {
1880            mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1881            mWindowAlignment.mainAxis().setMaxScroll(maxScroll);
1882            if (DEBUG) Log.v(getTag(), "updating scroll maxEdge to " + maxEdge +
1883                    " scrollMax to " + maxScroll);
1884        } else {
1885            mWindowAlignment.mainAxis().invalidateScrollMax();
1886            if (DEBUG) Log.v(getTag(), "Invalidate scrollMax since it should be "
1887                    + "greater than " + maxScroll);
1888        }
1889    }
1890
1891    private void updateScrollMin() {
1892        int lowVisiblePos = (!mReverseFlowPrimary) ? mGrid.getFirstVisibleIndex()
1893                : mGrid.getLastVisibleIndex();
1894        int lowMinPos = (!mReverseFlowPrimary) ? 0 : mState.getItemCount() - 1;
1895        if (lowVisiblePos < 0) {
1896            return;
1897        }
1898        final boolean lowAvailable = lowVisiblePos == lowMinPos;
1899        final boolean minUnknown = mWindowAlignment.mainAxis().isMinUnknown();
1900        if (!lowAvailable && minUnknown) {
1901            return;
1902        }
1903        int minEdge = mGrid.findRowMin(false, sTwoInts) + mScrollOffsetPrimary;
1904        int rowIndex = sTwoInts[0];
1905        int pos = sTwoInts[1];
1906        int savedMinEdge = mWindowAlignment.mainAxis().getMinEdge();
1907        mWindowAlignment.mainAxis().setMinEdge(minEdge);
1908        int minScroll = getPrimarySystemScrollPosition(findViewByPosition(pos));
1909        mWindowAlignment.mainAxis().setMinEdge(savedMinEdge);
1910
1911        if (lowAvailable) {
1912            mWindowAlignment.mainAxis().setMinEdge(minEdge);
1913            mWindowAlignment.mainAxis().setMinScroll(minScroll);
1914            if (DEBUG) Log.v(getTag(), "updating scroll minEdge to " + minEdge +
1915                    " scrollMin to " + minScroll);
1916        } else {
1917            mWindowAlignment.mainAxis().invalidateScrollMin();
1918            if (DEBUG) Log.v(getTag(), "Invalidate scrollMin, since it should be "
1919                    + "less than " + minScroll);
1920        }
1921    }
1922
1923    private void updateScrollSecondAxis() {
1924        mWindowAlignment.secondAxis().setMinEdge(0);
1925        mWindowAlignment.secondAxis().setMaxEdge(getSizeSecondary());
1926    }
1927
1928    private void initScrollController() {
1929        mWindowAlignment.reset();
1930        mWindowAlignment.horizontal.setSize(getWidth());
1931        mWindowAlignment.vertical.setSize(getHeight());
1932        mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight());
1933        mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom());
1934        mSizePrimary = mWindowAlignment.mainAxis().getSize();
1935        mScrollOffsetPrimary = -mWindowAlignment.mainAxis().getPaddingLow();
1936        mScrollOffsetSecondary = -mWindowAlignment.secondAxis().getPaddingLow();
1937
1938        if (DEBUG) {
1939            Log.v(getTag(), "initScrollController mSizePrimary " + mSizePrimary
1940                    + " mWindowAlignment " + mWindowAlignment
1941                    + " mScrollOffsetPrimary " + mScrollOffsetPrimary);
1942        }
1943    }
1944
1945    private void updateScrollController() {
1946        // mScrollOffsetPrimary and mScrollOffsetSecondary includes the padding.
1947        // e.g. when topPadding is 16 for horizontal grid view,  the initial
1948        // mScrollOffsetSecondary is -16.  fastRelayout() put views based on offsets(not padding),
1949        // when padding changes to 20,  we also need update mScrollOffsetSecondary to -20 before
1950        // fastRelayout() is performed
1951        int paddingPrimaryDiff, paddingSecondaryDiff;
1952        if (mOrientation == HORIZONTAL) {
1953            paddingPrimaryDiff = getPaddingLeft() - mWindowAlignment.horizontal.getPaddingLow();
1954            paddingSecondaryDiff = getPaddingTop() - mWindowAlignment.vertical.getPaddingLow();
1955        } else {
1956            paddingPrimaryDiff = getPaddingTop() - mWindowAlignment.vertical.getPaddingLow();
1957            paddingSecondaryDiff = getPaddingLeft() - mWindowAlignment.horizontal.getPaddingLow();
1958        }
1959        mScrollOffsetPrimary -= paddingPrimaryDiff;
1960        mScrollOffsetSecondary -= paddingSecondaryDiff;
1961
1962        mWindowAlignment.horizontal.setSize(getWidth());
1963        mWindowAlignment.vertical.setSize(getHeight());
1964        mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight());
1965        mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom());
1966        mSizePrimary = mWindowAlignment.mainAxis().getSize();
1967
1968        if (DEBUG) {
1969            Log.v(getTag(), "updateScrollController mSizePrimary " + mSizePrimary
1970                    + " mWindowAlignment " + mWindowAlignment
1971                    + " mScrollOffsetPrimary " + mScrollOffsetPrimary);
1972        }
1973    }
1974
1975    public void setSelection(RecyclerView parent, int position,
1976            int primaryScrollExtra) {
1977        setSelection(parent, position, false, primaryScrollExtra);
1978    }
1979
1980    public void setSelectionSmooth(RecyclerView parent, int position) {
1981        setSelection(parent, position, true, 0);
1982    }
1983
1984    public int getSelection() {
1985        return mFocusPosition;
1986    }
1987
1988    public void setSelection(RecyclerView parent, int position, boolean smooth,
1989            int primaryScrollExtra) {
1990        if (mFocusPosition != position && position != NO_POSITION
1991                || primaryScrollExtra != mPrimaryScrollExtra) {
1992            scrollToSelection(parent, position, smooth, primaryScrollExtra);
1993        }
1994    }
1995
1996    private void scrollToSelection(RecyclerView parent, int position, boolean smooth,
1997            int primaryScrollExtra) {
1998        if (TRACE) TraceHelper.beginSection("scrollToSelection");
1999        mPrimaryScrollExtra = primaryScrollExtra;
2000        View view = findViewByPosition(position);
2001        if (view != null) {
2002            mInSelection = true;
2003            scrollToView(view, smooth);
2004            mInSelection = false;
2005        } else {
2006            mFocusPosition = position;
2007            mFocusPositionOffset = 0;
2008            if (!mLayoutEnabled) {
2009                return;
2010            }
2011            if (smooth) {
2012                if (!hasDoneFirstLayout()) {
2013                    Log.w(getTag(), "setSelectionSmooth should " +
2014                            "not be called before first layout pass");
2015                    return;
2016                }
2017                startPositionSmoothScroller(position);
2018            } else {
2019                mForceFullLayout = true;
2020                parent.requestLayout();
2021            }
2022        }
2023        if (TRACE) TraceHelper.endSection();
2024    }
2025
2026    void startPositionSmoothScroller(int position) {
2027        LinearSmoothScroller linearSmoothScroller = new GridLinearSmoothScroller() {
2028            @Override
2029            public PointF computeScrollVectorForPosition(int targetPosition) {
2030                if (getChildCount() == 0) {
2031                    return null;
2032                }
2033                final int firstChildPos = getPosition(getChildAt(0));
2034                // TODO We should be able to deduce direction from bounds of current and target
2035                // focus, rather than making assumptions about positions and directionality
2036                final boolean isStart = mReverseFlowPrimary ? targetPosition > firstChildPos
2037                        : targetPosition < firstChildPos;
2038                final int direction = isStart ? -1 : 1;
2039                if (mOrientation == HORIZONTAL) {
2040                    return new PointF(direction, 0);
2041                } else {
2042                    return new PointF(0, direction);
2043                }
2044            }
2045
2046        };
2047        linearSmoothScroller.setTargetPosition(position);
2048        startSmoothScroll(linearSmoothScroller);
2049    }
2050
2051    private void processPendingMovement(boolean forward) {
2052        if (forward ? hasCreatedLastItem() : hasCreatedFirstItem()) {
2053            return;
2054        }
2055        if (mPendingMoveSmoothScroller == null) {
2056            // Stop existing scroller and create a new PendingMoveSmoothScroller.
2057            mBaseGridView.stopScroll();
2058            PendingMoveSmoothScroller linearSmoothScroller = new PendingMoveSmoothScroller(
2059                    forward ? 1 : -1, mNumRows > 1);
2060            mFocusPositionOffset = 0;
2061            startSmoothScroll(linearSmoothScroller);
2062            if (linearSmoothScroller.isRunning()) {
2063                mPendingMoveSmoothScroller = linearSmoothScroller;
2064            }
2065        } else {
2066            if (forward) {
2067                mPendingMoveSmoothScroller.increasePendingMoves();
2068            } else {
2069                mPendingMoveSmoothScroller.decreasePendingMoves();
2070            }
2071        }
2072    }
2073
2074    @Override
2075    public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
2076        if (DEBUG) Log.v(getTag(), "onItemsAdded positionStart "
2077                + positionStart + " itemCount " + itemCount);
2078        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
2079            int pos = mFocusPosition + mFocusPositionOffset;
2080            if (positionStart <= pos) {
2081                mFocusPositionOffset += itemCount;
2082            }
2083        }
2084        mChildrenStates.clear();
2085    }
2086
2087    @Override
2088    public void onItemsChanged(RecyclerView recyclerView) {
2089        if (DEBUG) Log.v(getTag(), "onItemsChanged");
2090        mFocusPositionOffset = 0;
2091        mChildrenStates.clear();
2092    }
2093
2094    @Override
2095    public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) {
2096        if (DEBUG) Log.v(getTag(), "onItemsRemoved positionStart "
2097                + positionStart + " itemCount " + itemCount);
2098        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
2099            int pos = mFocusPosition + mFocusPositionOffset;
2100            if (positionStart <= pos) {
2101                if (positionStart + itemCount > pos) {
2102                    // stop updating offset after the focus item was removed
2103                    mFocusPositionOffset = Integer.MIN_VALUE;
2104                } else {
2105                    mFocusPositionOffset -= itemCount;
2106                }
2107            }
2108        }
2109        mChildrenStates.clear();
2110    }
2111
2112    @Override
2113    public void onItemsMoved(RecyclerView recyclerView, int fromPosition, int toPosition,
2114            int itemCount) {
2115        if (DEBUG) Log.v(getTag(), "onItemsMoved fromPosition "
2116                + fromPosition + " toPosition " + toPosition);
2117        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
2118            int pos = mFocusPosition + mFocusPositionOffset;
2119            if (fromPosition <= pos && pos < fromPosition + itemCount) {
2120                // moved items include focused position
2121                mFocusPositionOffset += toPosition - fromPosition;
2122            } else if (fromPosition < pos && toPosition > pos - itemCount) {
2123                // move items before focus position to after focused position
2124                mFocusPositionOffset -= itemCount;
2125            } else if (fromPosition > pos && toPosition < pos) {
2126                // move items after focus position to before focused position
2127                mFocusPositionOffset += itemCount;
2128            }
2129        }
2130        mChildrenStates.clear();
2131    }
2132
2133    @Override
2134    public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount) {
2135        if (DEBUG) Log.v(getTag(), "onItemsUpdated positionStart "
2136                + positionStart + " itemCount " + itemCount);
2137        for (int i = positionStart, end = positionStart + itemCount; i < end; i++) {
2138            mChildrenStates.remove(i);
2139        }
2140    }
2141
2142    @Override
2143    public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) {
2144        if (mFocusSearchDisabled) {
2145            return true;
2146        }
2147        if (getPositionByView(child) == NO_POSITION) {
2148            // This shouldn't happen, but in case it does be sure not to attempt a
2149            // scroll to a view whose item has been removed.
2150            return true;
2151        }
2152        if (!mInLayout && !mInSelection && !mInScroll) {
2153            scrollToView(child, true);
2154        }
2155        return true;
2156    }
2157
2158    @Override
2159    public boolean requestChildRectangleOnScreen(RecyclerView parent, View view, Rect rect,
2160            boolean immediate) {
2161        if (DEBUG) Log.v(getTag(), "requestChildRectangleOnScreen " + view + " " + rect);
2162        return false;
2163    }
2164
2165    int getScrollOffsetX() {
2166        return mOrientation == HORIZONTAL ? mScrollOffsetPrimary : mScrollOffsetSecondary;
2167    }
2168
2169    int getScrollOffsetY() {
2170        return mOrientation == HORIZONTAL ? mScrollOffsetSecondary : mScrollOffsetPrimary;
2171    }
2172
2173    public void getViewSelectedOffsets(View view, int[] offsets) {
2174        if (mOrientation == HORIZONTAL) {
2175            offsets[0] = getPrimarySystemScrollPosition(view) - mScrollOffsetPrimary;
2176            offsets[1] = getSecondarySystemScrollPosition(view) - mScrollOffsetSecondary;
2177        } else {
2178            offsets[1] = getPrimarySystemScrollPosition(view) - mScrollOffsetPrimary;
2179            offsets[0] = getSecondarySystemScrollPosition(view) - mScrollOffsetSecondary;
2180        }
2181    }
2182
2183    private int getPrimarySystemScrollPosition(View view) {
2184        final int viewCenterPrimary = mScrollOffsetPrimary + getViewCenter(view);
2185        final int viewMin = getViewMin(view);
2186        final int viewMax = getViewMax(view);
2187        // TODO: change to use State object in onRequestChildFocus()
2188        boolean isMin, isMax;
2189        if (!mReverseFlowPrimary) {
2190            isMin = mGrid.getFirstVisibleIndex() == 0;
2191            isMax = mGrid.getLastVisibleIndex() == (mState == null ?
2192                    getItemCount() : mState.getItemCount()) - 1;
2193        } else {
2194            isMax = mGrid.getFirstVisibleIndex() == 0;
2195            isMin = mGrid.getLastVisibleIndex() == (mState == null ?
2196                    getItemCount() : mState.getItemCount()) - 1;
2197        }
2198        for (int i = getChildCount() - 1; (isMin || isMax) && i >= 0; i--) {
2199            View v = getChildAt(i);
2200            if (v == view || v == null) {
2201                continue;
2202            }
2203            if (isMin && getViewMin(v) < viewMin) {
2204                isMin = false;
2205            }
2206            if (isMax && getViewMax(v) > viewMax) {
2207                isMax = false;
2208            }
2209        }
2210        return mWindowAlignment.mainAxis().getSystemScrollPos(viewCenterPrimary, isMin, isMax);
2211    }
2212
2213    private int getSecondarySystemScrollPosition(View view) {
2214        int viewCenterSecondary = mScrollOffsetSecondary + getViewCenterSecondary(view);
2215        int pos = getPositionByView(view);
2216        Grid.Location location = mGrid.getLocation(pos);
2217        final int row = location.row;
2218        final boolean isMin, isMax;
2219        if (!mReverseFlowSecondary) {
2220            isMin = row == 0;
2221            isMax = row == mGrid.getNumRows() - 1;
2222        } else {
2223            isMax = row == 0;
2224            isMin = row == mGrid.getNumRows() - 1;
2225        }
2226        return mWindowAlignment.secondAxis().getSystemScrollPos(viewCenterSecondary, isMin, isMax);
2227    }
2228
2229    /**
2230     * Scroll to a given child view and change mFocusPosition.
2231     */
2232    private void scrollToView(View view, boolean smooth) {
2233        int newFocusPosition = getPositionByView(view);
2234        if (newFocusPosition != mFocusPosition) {
2235            mFocusPosition = newFocusPosition;
2236            mFocusPositionOffset = 0;
2237            if (!mInLayout) {
2238                dispatchChildSelected();
2239            }
2240            if (mBaseGridView.isChildrenDrawingOrderEnabledInternal()) {
2241                mBaseGridView.invalidate();
2242            }
2243        }
2244        if (view == null) {
2245            return;
2246        }
2247        if (!view.hasFocus() && mBaseGridView.hasFocus()) {
2248            // transfer focus to the child if it does not have focus yet (e.g. triggered
2249            // by setSelection())
2250            view.requestFocus();
2251        }
2252        if (!mScrollEnabled && smooth) {
2253            return;
2254        }
2255        if (getScrollPosition(view, sTwoInts)) {
2256            scrollGrid(sTwoInts[0], sTwoInts[1], smooth);
2257        }
2258    }
2259
2260    private boolean getScrollPosition(View view, int[] deltas) {
2261        switch (mFocusScrollStrategy) {
2262        case BaseGridView.FOCUS_SCROLL_ALIGNED:
2263        default:
2264            return getAlignedPosition(view, deltas);
2265        case BaseGridView.FOCUS_SCROLL_ITEM:
2266        case BaseGridView.FOCUS_SCROLL_PAGE:
2267            return getNoneAlignedPosition(view, deltas);
2268        }
2269    }
2270
2271    private boolean getNoneAlignedPosition(View view, int[] deltas) {
2272        int pos = getPositionByView(view);
2273        int viewMin = getViewMin(view);
2274        int viewMax = getViewMax(view);
2275        // we either align "firstView" to left/top padding edge
2276        // or align "lastView" to right/bottom padding edge
2277        View firstView = null;
2278        View lastView = null;
2279        int paddingLow = mWindowAlignment.mainAxis().getPaddingLow();
2280        int clientSize = mWindowAlignment.mainAxis().getClientSize();
2281        final int row = mGrid.getRowIndex(pos);
2282        if (viewMin < paddingLow) {
2283            // view enters low padding area:
2284            firstView = view;
2285            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
2286                // scroll one "page" left/top,
2287                // align first visible item of the "page" at the low padding edge.
2288                while (prependOneColumnVisibleItems()) {
2289                    CircularIntArray positions =
2290                            mGrid.getItemPositionsInRows(mGrid.getFirstVisibleIndex(), pos)[row];
2291                    firstView = findViewByPosition(positions.get(0));
2292                    if (viewMax - getViewMin(firstView) > clientSize) {
2293                        if (positions.size() > 2) {
2294                            firstView = findViewByPosition(positions.get(2));
2295                        }
2296                        break;
2297                    }
2298                }
2299            }
2300        } else if (viewMax > clientSize + paddingLow) {
2301            // view enters high padding area:
2302            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
2303                // scroll whole one page right/bottom, align view at the low padding edge.
2304                firstView = view;
2305                do {
2306                    CircularIntArray positions =
2307                            mGrid.getItemPositionsInRows(pos, mGrid.getLastVisibleIndex())[row];
2308                    lastView = findViewByPosition(positions.get(positions.size() - 1));
2309                    if (getViewMax(lastView) - viewMin > clientSize) {
2310                        lastView = null;
2311                        break;
2312                    }
2313                } while (appendOneColumnVisibleItems());
2314                if (lastView != null) {
2315                    // however if we reached end,  we should align last view.
2316                    firstView = null;
2317                }
2318            } else {
2319                lastView = view;
2320            }
2321        }
2322        int scrollPrimary = 0;
2323        int scrollSecondary = 0;
2324        if (firstView != null) {
2325            scrollPrimary = getViewMin(firstView) - paddingLow;
2326        } else if (lastView != null) {
2327            scrollPrimary = getViewMax(lastView) - (paddingLow + clientSize);
2328        }
2329        View secondaryAlignedView;
2330        if (firstView != null) {
2331            secondaryAlignedView = firstView;
2332        } else if (lastView != null) {
2333            secondaryAlignedView = lastView;
2334        } else {
2335            secondaryAlignedView = view;
2336        }
2337        scrollSecondary = getSecondarySystemScrollPosition(secondaryAlignedView);
2338        scrollSecondary -= mScrollOffsetSecondary;
2339        if (scrollPrimary != 0 || scrollSecondary != 0) {
2340            deltas[0] = scrollPrimary;
2341            deltas[1] = scrollSecondary;
2342            return true;
2343        }
2344        return false;
2345    }
2346
2347    private boolean getAlignedPosition(View view, int[] deltas) {
2348        int scrollPrimary = getPrimarySystemScrollPosition(view);
2349        int scrollSecondary = getSecondarySystemScrollPosition(view);
2350        if (DEBUG) {
2351            Log.v(getTag(), "getAlignedPosition " + scrollPrimary + " " + scrollSecondary
2352                    + " " + mPrimaryScrollExtra + " " + mWindowAlignment);
2353            Log.v(getTag(), "getAlignedPosition " + mScrollOffsetPrimary + " " + mScrollOffsetSecondary);
2354        }
2355        scrollPrimary -= mScrollOffsetPrimary;
2356        scrollSecondary -= mScrollOffsetSecondary;
2357        scrollPrimary += mPrimaryScrollExtra;
2358        if (scrollPrimary != 0 || scrollSecondary != 0) {
2359            deltas[0] = scrollPrimary;
2360            deltas[1] = scrollSecondary;
2361            return true;
2362        }
2363        return false;
2364    }
2365
2366    private void scrollGrid(int scrollPrimary, int scrollSecondary, boolean smooth) {
2367        if (mInLayout) {
2368            scrollDirectionPrimary(scrollPrimary);
2369            scrollDirectionSecondary(scrollSecondary);
2370        } else {
2371            int scrollX;
2372            int scrollY;
2373            if (mOrientation == HORIZONTAL) {
2374                scrollX = scrollPrimary;
2375                scrollY = scrollSecondary;
2376            } else {
2377                scrollX = scrollSecondary;
2378                scrollY = scrollPrimary;
2379            }
2380            if (smooth) {
2381                mBaseGridView.smoothScrollBy(scrollX, scrollY);
2382            } else {
2383                mBaseGridView.scrollBy(scrollX, scrollY);
2384            }
2385        }
2386    }
2387
2388    public void setPruneChild(boolean pruneChild) {
2389        if (mPruneChild != pruneChild) {
2390            mPruneChild = pruneChild;
2391            if (mPruneChild) {
2392                requestLayout();
2393            }
2394        }
2395    }
2396
2397    public boolean getPruneChild() {
2398        return mPruneChild;
2399    }
2400
2401    public void setScrollEnabled(boolean scrollEnabled) {
2402        if (mScrollEnabled != scrollEnabled) {
2403            mScrollEnabled = scrollEnabled;
2404            if (mScrollEnabled && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED
2405                    && mFocusPosition != NO_POSITION) {
2406                scrollToSelection(mBaseGridView, mFocusPosition, true, mPrimaryScrollExtra);
2407            }
2408        }
2409    }
2410
2411    public boolean isScrollEnabled() {
2412        return mScrollEnabled;
2413    }
2414
2415    private int findImmediateChildIndex(View view) {
2416        while (view != null && view != mBaseGridView) {
2417            int index = mBaseGridView.indexOfChild(view);
2418            if (index >= 0) {
2419                return index;
2420            }
2421            view = (View) view.getParent();
2422        }
2423        return NO_POSITION;
2424    }
2425
2426    void setFocusSearchDisabled(boolean disabled) {
2427        mFocusSearchDisabled = disabled;
2428    }
2429
2430    boolean isFocusSearchDisabled() {
2431        return mFocusSearchDisabled;
2432    }
2433
2434    @Override
2435    public View onInterceptFocusSearch(View focused, int direction) {
2436        if (mFocusSearchDisabled) {
2437            return focused;
2438        }
2439        return null;
2440    }
2441
2442    boolean hasPreviousViewInSameRow(int pos) {
2443        if (mGrid == null || pos == NO_POSITION || mGrid.getFirstVisibleIndex() < 0) {
2444            return false;
2445        }
2446        if (mGrid.getFirstVisibleIndex() > 0) {
2447            return true;
2448        }
2449        final int focusedRow = mGrid.getLocation(pos).row;
2450        for (int i = getChildCount() - 1; i >= 0; i--) {
2451            int position = getPositionByIndex(i);
2452            Grid.Location loc = mGrid.getLocation(position);
2453            if (loc != null && loc.row == focusedRow) {
2454                if (position < pos) {
2455                    return true;
2456                }
2457            }
2458        }
2459        return false;
2460    }
2461
2462    @Override
2463    public boolean onAddFocusables(RecyclerView recyclerView,
2464            ArrayList<View> views, int direction, int focusableMode) {
2465        if (mFocusSearchDisabled) {
2466            return true;
2467        }
2468        // If this viewgroup or one of its children currently has focus then we
2469        // consider our children for focus searching in main direction on the same row.
2470        // If this viewgroup has no focus and using focus align, we want the system
2471        // to ignore our children and pass focus to the viewgroup, which will pass
2472        // focus on to its children appropriately.
2473        // If this viewgroup has no focus and not using focus align, we want to
2474        // consider the child that does not overlap with padding area.
2475        if (recyclerView.hasFocus()) {
2476            final int movement = getMovement(direction);
2477            if (movement != PREV_ITEM && movement != NEXT_ITEM) {
2478                // Move on secondary direction uses default addFocusables().
2479                return false;
2480            }
2481            if (mPendingMoveSmoothScroller != null) {
2482                // don't find next focusable if has pending movement.
2483                return true;
2484            }
2485            final View focused = recyclerView.findFocus();
2486            final int focusedPos = getPositionByIndex(findImmediateChildIndex(focused));
2487            // Add focusables of focused item.
2488            if (focusedPos != NO_POSITION) {
2489                findViewByPosition(focusedPos).addFocusables(views,  direction, focusableMode);
2490            }
2491            final int focusedRow = mGrid != null && focusedPos != NO_POSITION ?
2492                    mGrid.getLocation(focusedPos).row : NO_POSITION;
2493            // Add focusables of next neighbor of same row on the focus search direction.
2494            if (mGrid != null) {
2495                final int focusableCount = views.size();
2496                for (int i = 0, count = getChildCount(); i < count; i++) {
2497                    int index = movement == NEXT_ITEM ? i : count - 1 - i;
2498                    final View child = getChildAt(index);
2499                    if (child.getVisibility() != View.VISIBLE || !child.hasFocusable()) {
2500                        continue;
2501                    }
2502                    int position = getPositionByIndex(index);
2503                    Grid.Location loc = mGrid.getLocation(position);
2504                    if (focusedRow == NO_POSITION || (loc != null && loc.row == focusedRow)) {
2505                        if (focusedPos == NO_POSITION ||
2506                                (movement == NEXT_ITEM && position > focusedPos)
2507                                || (movement == PREV_ITEM && position < focusedPos)) {
2508                            child.addFocusables(views,  direction, focusableMode);
2509                            if (views.size() > focusableCount) {
2510                                break;
2511                            }
2512                        }
2513                    }
2514                }
2515            }
2516        } else {
2517            if (mFocusScrollStrategy != BaseGridView.FOCUS_SCROLL_ALIGNED) {
2518                // adding views not overlapping padding area to avoid scrolling in gaining focus
2519                int left = mWindowAlignment.mainAxis().getPaddingLow();
2520                int right = mWindowAlignment.mainAxis().getClientSize() + left;
2521                int focusableCount = views.size();
2522                for (int i = 0, count = getChildCount(); i < count; i++) {
2523                    View child = getChildAt(i);
2524                    if (child.getVisibility() == View.VISIBLE) {
2525                        if (getViewMin(child) >= left && getViewMax(child) <= right) {
2526                            child.addFocusables(views, direction, focusableMode);
2527                        }
2528                    }
2529                }
2530                // if we cannot find any, then just add all children.
2531                if (views.size() == focusableCount) {
2532                    for (int i = 0, count = getChildCount(); i < count; i++) {
2533                        View child = getChildAt(i);
2534                        if (child.getVisibility() == View.VISIBLE) {
2535                            child.addFocusables(views, direction, focusableMode);
2536                        }
2537                    }
2538                    if (views.size() != focusableCount) {
2539                        return true;
2540                    }
2541                } else {
2542                    return true;
2543                }
2544                // if still cannot find any, fall through and add itself
2545            }
2546            if (recyclerView.isFocusable()) {
2547                views.add(recyclerView);
2548            }
2549        }
2550        return true;
2551    }
2552
2553    private boolean hasCreatedLastItem() {
2554        int count = mState.getItemCount();
2555        return count == 0 || findViewByPosition(count - 1) != null;
2556    }
2557
2558    private boolean hasCreatedFirstItem() {
2559        int count = mState.getItemCount();
2560        return count == 0 || findViewByPosition(0) != null;
2561    }
2562
2563    boolean canScrollTo(View view) {
2564        return view.getVisibility() == View.VISIBLE && (!hasFocus() || view.hasFocusable());
2565    }
2566
2567    @Override
2568    public View onFocusSearchFailed(View focused, int direction, Recycler recycler,
2569            RecyclerView.State state) {
2570        if (DEBUG) Log.v(getTag(), "onFocusSearchFailed direction " + direction);
2571
2572        View view = null;
2573        int movement = getMovement(direction);
2574        final boolean isScroll = mBaseGridView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE;
2575        saveContext(recycler, state);
2576        if (movement == NEXT_ITEM) {
2577            if (isScroll || !mFocusOutEnd) {
2578                view = focused;
2579            }
2580            if (mScrollEnabled && !hasCreatedLastItem()) {
2581                processPendingMovement(true);
2582                view = focused;
2583            }
2584        } else if (movement == PREV_ITEM) {
2585            if (isScroll || !mFocusOutFront) {
2586                view = focused;
2587            }
2588            if (mScrollEnabled && !hasCreatedFirstItem()) {
2589                processPendingMovement(false);
2590                view = focused;
2591            }
2592        }
2593        leaveContext();
2594        if (DEBUG) Log.v(getTag(), "onFocusSearchFailed returning view " + view);
2595        return view;
2596    }
2597
2598    boolean gridOnRequestFocusInDescendants(RecyclerView recyclerView, int direction,
2599            Rect previouslyFocusedRect) {
2600        switch (mFocusScrollStrategy) {
2601        case BaseGridView.FOCUS_SCROLL_ALIGNED:
2602        default:
2603            return gridOnRequestFocusInDescendantsAligned(recyclerView,
2604                    direction, previouslyFocusedRect);
2605        case BaseGridView.FOCUS_SCROLL_PAGE:
2606        case BaseGridView.FOCUS_SCROLL_ITEM:
2607            return gridOnRequestFocusInDescendantsUnaligned(recyclerView,
2608                    direction, previouslyFocusedRect);
2609        }
2610    }
2611
2612    private boolean gridOnRequestFocusInDescendantsAligned(RecyclerView recyclerView,
2613            int direction, Rect previouslyFocusedRect) {
2614        View view = findViewByPosition(mFocusPosition);
2615        if (view != null) {
2616            boolean result = view.requestFocus(direction, previouslyFocusedRect);
2617            if (!result && DEBUG) {
2618                Log.w(getTag(), "failed to request focus on " + view);
2619            }
2620            return result;
2621        }
2622        return false;
2623    }
2624
2625    private boolean gridOnRequestFocusInDescendantsUnaligned(RecyclerView recyclerView,
2626            int direction, Rect previouslyFocusedRect) {
2627        // focus to view not overlapping padding area to avoid scrolling in gaining focus
2628        int index;
2629        int increment;
2630        int end;
2631        int count = getChildCount();
2632        if ((direction & View.FOCUS_FORWARD) != 0) {
2633            index = 0;
2634            increment = 1;
2635            end = count;
2636        } else {
2637            index = count - 1;
2638            increment = -1;
2639            end = -1;
2640        }
2641        int left = mWindowAlignment.mainAxis().getPaddingLow();
2642        int right = mWindowAlignment.mainAxis().getClientSize() + left;
2643        for (int i = index; i != end; i += increment) {
2644            View child = getChildAt(i);
2645            if (child.getVisibility() == View.VISIBLE) {
2646                if (getViewMin(child) >= left && getViewMax(child) <= right) {
2647                    if (child.requestFocus(direction, previouslyFocusedRect)) {
2648                        return true;
2649                    }
2650                }
2651            }
2652        }
2653        return false;
2654    }
2655
2656    private final static int PREV_ITEM = 0;
2657    private final static int NEXT_ITEM = 1;
2658    private final static int PREV_ROW = 2;
2659    private final static int NEXT_ROW = 3;
2660
2661    private int getMovement(int direction) {
2662        int movement = View.FOCUS_LEFT;
2663
2664        if (mOrientation == HORIZONTAL) {
2665            switch(direction) {
2666                case View.FOCUS_LEFT:
2667                    movement = (!mReverseFlowPrimary) ? PREV_ITEM : NEXT_ITEM;
2668                    break;
2669                case View.FOCUS_RIGHT:
2670                    movement = (!mReverseFlowPrimary) ? NEXT_ITEM : PREV_ITEM;
2671                    break;
2672                case View.FOCUS_UP:
2673                    movement = PREV_ROW;
2674                    break;
2675                case View.FOCUS_DOWN:
2676                    movement = NEXT_ROW;
2677                    break;
2678            }
2679         } else if (mOrientation == VERTICAL) {
2680             switch(direction) {
2681                 case View.FOCUS_LEFT:
2682                     movement = (!mReverseFlowPrimary) ? PREV_ROW : NEXT_ROW;
2683                     break;
2684                 case View.FOCUS_RIGHT:
2685                     movement = (!mReverseFlowPrimary) ? NEXT_ROW : PREV_ROW;
2686                     break;
2687                 case View.FOCUS_UP:
2688                     movement = PREV_ITEM;
2689                     break;
2690                 case View.FOCUS_DOWN:
2691                     movement = NEXT_ITEM;
2692                     break;
2693             }
2694         }
2695
2696        return movement;
2697    }
2698
2699    int getChildDrawingOrder(RecyclerView recyclerView, int childCount, int i) {
2700        View view = findViewByPosition(mFocusPosition);
2701        if (view == null) {
2702            return i;
2703        }
2704        int focusIndex = recyclerView.indexOfChild(view);
2705        // supposely 0 1 2 3 4 5 6 7 8 9, 4 is the center item
2706        // drawing order is 0 1 2 3 9 8 7 6 5 4
2707        if (i < focusIndex) {
2708            return i;
2709        } else if (i < childCount - 1) {
2710            return focusIndex + childCount - 1 - i;
2711        } else {
2712            return focusIndex;
2713        }
2714    }
2715
2716    @Override
2717    public void onAdapterChanged(RecyclerView.Adapter oldAdapter,
2718            RecyclerView.Adapter newAdapter) {
2719        if (DEBUG) Log.v(getTag(), "onAdapterChanged to " + newAdapter);
2720        if (oldAdapter != null) {
2721            discardLayoutInfo();
2722            mFocusPosition = NO_POSITION;
2723            mFocusPositionOffset = 0;
2724            mChildrenStates.clear();
2725        }
2726        super.onAdapterChanged(oldAdapter, newAdapter);
2727    }
2728
2729    private void discardLayoutInfo() {
2730        mGrid = null;
2731        mRowSizeSecondary = null;
2732        mRowSecondarySizeRefresh = false;
2733    }
2734
2735    public void setLayoutEnabled(boolean layoutEnabled) {
2736        if (mLayoutEnabled != layoutEnabled) {
2737            mLayoutEnabled = layoutEnabled;
2738            requestLayout();
2739        }
2740    }
2741
2742    void setChildrenVisibility(int visiblity) {
2743        mChildVisibility = visiblity;
2744        if (mChildVisibility != -1) {
2745            int count = getChildCount();
2746            for (int i= 0; i < count; i++) {
2747                getChildAt(i).setVisibility(mChildVisibility);
2748            }
2749        }
2750    }
2751
2752    final static class SavedState implements Parcelable {
2753
2754        int index; // index inside adapter of the current view
2755        Bundle childStates = Bundle.EMPTY;
2756
2757        @Override
2758        public void writeToParcel(Parcel out, int flags) {
2759            out.writeInt(index);
2760            out.writeBundle(childStates);
2761        }
2762
2763        @SuppressWarnings("hiding")
2764        public static final Parcelable.Creator<SavedState> CREATOR =
2765                new Parcelable.Creator<SavedState>() {
2766                    @Override
2767                    public SavedState createFromParcel(Parcel in) {
2768                        return new SavedState(in);
2769                    }
2770
2771                    @Override
2772                    public SavedState[] newArray(int size) {
2773                        return new SavedState[size];
2774                    }
2775                };
2776
2777        @Override
2778        public int describeContents() {
2779            return 0;
2780        }
2781
2782        SavedState(Parcel in) {
2783            index = in.readInt();
2784            childStates = in.readBundle(GridLayoutManager.class.getClassLoader());
2785        }
2786
2787        SavedState() {
2788        }
2789    }
2790
2791    @Override
2792    public Parcelable onSaveInstanceState() {
2793        if (DEBUG) Log.v(getTag(), "onSaveInstanceState getSelection() " + getSelection());
2794        SavedState ss = new SavedState();
2795        for (int i = 0, count = getChildCount(); i < count; i++) {
2796            View view = getChildAt(i);
2797            int position = getPositionByView(view);
2798            if (position != NO_POSITION) {
2799                mChildrenStates.saveOnScreenView(view, position);
2800            }
2801        }
2802        ss.index = getSelection();
2803        ss.childStates = mChildrenStates.saveAsBundle();
2804        return ss;
2805    }
2806
2807    void onChildRecycled(RecyclerView.ViewHolder holder) {
2808        final int position = holder.getAdapterPosition();
2809        if (position != NO_POSITION) {
2810            mChildrenStates.saveOffscreenView(holder.itemView, position);
2811        }
2812    }
2813
2814    @Override
2815    public void onRestoreInstanceState(Parcelable state) {
2816        if (!(state instanceof SavedState)) {
2817            return;
2818        }
2819        SavedState loadingState = (SavedState)state;
2820        mFocusPosition = loadingState.index;
2821        mFocusPositionOffset = 0;
2822        mChildrenStates.loadFromBundle(loadingState.childStates);
2823        mForceFullLayout = true;
2824        requestLayout();
2825        if (DEBUG) Log.v(getTag(), "onRestoreInstanceState mFocusPosition " + mFocusPosition);
2826    }
2827}
2828