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