GridLayoutManager.java revision ca5ab1a00298f1c1ad5227e352b8ae2e67c079a7
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.AccessibilityNodeInfoCompat;
25import android.support.v7.widget.LinearSmoothScroller;
26import android.support.v7.widget.RecyclerView;
27import android.support.v7.widget.RecyclerView.Recycler;
28import android.support.v7.widget.RecyclerView.State;
29import android.support.v17.leanback.os.TraceHelper;
30
31import static android.support.v7.widget.RecyclerView.NO_ID;
32import static android.support.v7.widget.RecyclerView.NO_POSITION;
33import static android.support.v7.widget.RecyclerView.HORIZONTAL;
34import static android.support.v7.widget.RecyclerView.VERTICAL;
35
36import android.util.AttributeSet;
37import android.util.Log;
38import android.view.Gravity;
39import android.view.View;
40import android.view.View.MeasureSpec;
41import android.view.ViewGroup.MarginLayoutParams;
42import android.view.ViewGroup;
43
44import java.io.PrintWriter;
45import java.io.StringWriter;
46import java.util.ArrayList;
47
48final class GridLayoutManager extends RecyclerView.LayoutManager {
49
50     /*
51      * LayoutParams for {@link HorizontalGridView} and {@link VerticalGridView}.
52      * The class currently does two internal jobs:
53      * - Saves optical bounds insets.
54      * - Caches focus align view center.
55      */
56    final static class LayoutParams extends RecyclerView.LayoutParams {
57
58        // For placement
59        private int mLeftInset;
60        private int mTopInset;
61        private int mRightInset;
62        private int mBottomInset;
63
64        // For alignment
65        private int mAlignX;
66        private int mAlignY;
67        private int[] mAlignMultiple;
68        private ItemAlignmentFacet mAlignmentFacet;
69
70        public LayoutParams(Context c, AttributeSet attrs) {
71            super(c, attrs);
72        }
73
74        public LayoutParams(int width, int height) {
75            super(width, height);
76        }
77
78        public LayoutParams(MarginLayoutParams source) {
79            super(source);
80        }
81
82        public LayoutParams(ViewGroup.LayoutParams source) {
83            super(source);
84        }
85
86        public LayoutParams(RecyclerView.LayoutParams source) {
87            super(source);
88        }
89
90        public LayoutParams(LayoutParams source) {
91            super(source);
92        }
93
94        int getAlignX() {
95            return mAlignX;
96        }
97
98        int getAlignY() {
99            return mAlignY;
100        }
101
102        int getOpticalLeft(View view) {
103            return view.getLeft() + mLeftInset;
104        }
105
106        int getOpticalTop(View view) {
107            return view.getTop() + mTopInset;
108        }
109
110        int getOpticalRight(View view) {
111            return view.getRight() - mRightInset;
112        }
113
114        int getOpticalBottom(View view) {
115            return view.getBottom() - mBottomInset;
116        }
117
118        int getOpticalWidth(View view) {
119            return view.getWidth() - mLeftInset - mRightInset;
120        }
121
122        int getOpticalHeight(View view) {
123            return view.getHeight() - mTopInset - mBottomInset;
124        }
125
126        int getDecoratedOpticalLeftWithMargin(RecyclerView.LayoutManager lm, View view) {
127            return lm.getDecoratedLeft(view) + mLeftInset - leftMargin;
128        }
129
130        int getDecoratedOpticalTopWithMargin(RecyclerView.LayoutManager lm, View view) {
131            return lm.getDecoratedTop(view) + mTopInset - topMargin;
132        }
133
134        int getDecoratedOpticalRightWithMargin(RecyclerView.LayoutManager lm, View view) {
135            return lm.getDecoratedRight(view) - mRightInset + rightMargin;
136        }
137
138        int getDecoratedOpticalBottomWithMargin(RecyclerView.LayoutManager lm, View view) {
139            return lm.getDecoratedBottom(view) - mBottomInset + bottomMargin;
140        }
141
142        int getDecoratedOpticalWidthWithMargin(RecyclerView.LayoutManager lm, View view) {
143            return lm.getDecoratedRight(view) - lm.getDecoratedLeft(view)
144                    - mLeftInset - mRightInset + leftMargin + rightMargin;
145        }
146
147        int getDecoratedOpticalHeightWithMargin(RecyclerView.LayoutManager lm, View view) {
148            return lm.getDecoratedBottom(view) - lm.getDecoratedTop(view)
149                    - mTopInset - mBottomInset + topMargin + bottomMargin;
150        }
151
152        int getOpticalLeftInset() {
153            return mLeftInset;
154        }
155
156        int getOpticalRightInset() {
157            return mRightInset;
158        }
159
160        int getOpticalTopInset() {
161            return mTopInset;
162        }
163
164        int getOpticalBottomInset() {
165            return mBottomInset;
166        }
167
168        void setAlignX(int alignX) {
169            mAlignX = alignX;
170        }
171
172        void setAlignY(int alignY) {
173            mAlignY = alignY;
174        }
175
176        void setItemAlignmentFacet(ItemAlignmentFacet facet) {
177            mAlignmentFacet = facet;
178        }
179
180        ItemAlignmentFacet getItemAlignmentFacet() {
181            return mAlignmentFacet;
182        }
183
184        void calculateItemAlignments(int orientation, View view) {
185            ItemAlignmentFacet.ItemAlignmentDef[] defs = mAlignmentFacet.getAlignmentDefs();
186            if (mAlignMultiple == null || mAlignMultiple.length != defs.length) {
187                mAlignMultiple = new int[defs.length];
188            }
189            for (int i = 0; i < defs.length; i++) {
190                mAlignMultiple[i] = ItemAlignmentFacetHelper
191                        .getAlignmentPosition(view, defs[i], orientation);
192            }
193            if (orientation == HORIZONTAL) {
194                mAlignX = mAlignMultiple[0];
195            } else {
196                mAlignY = mAlignMultiple[0];
197            }
198        }
199
200        int[] getAlignMultiple() {
201            return mAlignMultiple;
202        }
203
204        void setOpticalInsets(int leftInset, int topInset, int rightInset, int bottomInset) {
205            mLeftInset = leftInset;
206            mTopInset = topInset;
207            mRightInset = rightInset;
208            mBottomInset = bottomInset;
209        }
210
211    }
212
213    /**
214     * Base class which scrolls to selected view in onStop().
215     */
216    abstract class GridLinearSmoothScroller extends LinearSmoothScroller {
217        GridLinearSmoothScroller() {
218            super(mBaseGridView.getContext());
219        }
220
221        @Override
222        protected void onStop() {
223            // onTargetFound() may not be called if we hit the "wall" first or get cancelled.
224            View targetView = findViewByPosition(getTargetPosition());
225            if (targetView == null) {
226                if (getTargetPosition() >= 0) {
227                    // if smooth scroller is stopped without target, immediately jumps
228                    // to the target position.
229                    scrollToSelection(getTargetPosition(), 0, false, 0);
230                }
231                super.onStop();
232                return;
233            }
234            if (hasFocus()) {
235                mInSelection = true;
236                targetView.requestFocus();
237                mInSelection = false;
238            }
239            dispatchChildSelected();
240            super.onStop();
241        }
242
243        @Override
244        protected int calculateTimeForScrolling(int dx) {
245            int ms = super.calculateTimeForScrolling(dx);
246            if (mWindowAlignment.mainAxis().getSize() > 0) {
247                float minMs = (float) MIN_MS_SMOOTH_SCROLL_MAIN_SCREEN /
248                        mWindowAlignment.mainAxis().getSize() * dx;
249                if (ms < minMs) {
250                    ms = (int) minMs;
251                }
252            }
253            return ms;
254        }
255
256        @Override
257        protected void onTargetFound(View targetView,
258                RecyclerView.State state, Action action) {
259            if (getScrollPosition(targetView, null, sTwoInts)) {
260                int dx, dy;
261                if (mOrientation == HORIZONTAL) {
262                    dx = sTwoInts[0];
263                    dy = sTwoInts[1];
264                } else {
265                    dx = sTwoInts[1];
266                    dy = sTwoInts[0];
267                }
268                final int distance = (int) Math.sqrt(dx * dx + dy * dy);
269                final int time = calculateTimeForDeceleration(distance);
270                action.update(dx, dy, time, mDecelerateInterpolator);
271            }
272        }
273    }
274
275    /**
276     * The SmoothScroller that remembers pending DPAD keys and consume pending keys
277     * during scroll.
278     */
279    final class PendingMoveSmoothScroller extends GridLinearSmoothScroller {
280        // -2 is a target position that LinearSmoothScroller can never find until
281        // consumePendingMovesXXX() sets real targetPosition.
282        final static int TARGET_UNDEFINED = -2;
283        // whether the grid is staggered.
284        private final boolean mStaggeredGrid;
285        // Number of pending movements on primary direction, negative if PREV_ITEM.
286        private int mPendingMoves;
287
288        PendingMoveSmoothScroller(int initialPendingMoves, boolean staggeredGrid) {
289            mPendingMoves = initialPendingMoves;
290            mStaggeredGrid = staggeredGrid;
291            setTargetPosition(TARGET_UNDEFINED);
292        }
293
294        void increasePendingMoves() {
295            if (mPendingMoves < MAX_PENDING_MOVES) {
296                mPendingMoves++;
297            }
298        }
299
300        void decreasePendingMoves() {
301            if (mPendingMoves > -MAX_PENDING_MOVES) {
302                mPendingMoves--;
303            }
304        }
305
306        /**
307         * Called before laid out an item when non-staggered grid can handle pending movements
308         * by skipping "mNumRows" per movement;  staggered grid will have to wait the item
309         * has been laid out in consumePendingMovesAfterLayout().
310         */
311        void consumePendingMovesBeforeLayout() {
312            if (mStaggeredGrid || mPendingMoves == 0) {
313                return;
314            }
315            View newSelected = null;
316            int startPos = mPendingMoves > 0 ? mFocusPosition + mNumRows :
317                    mFocusPosition - mNumRows;
318            for (int pos = startPos; mPendingMoves != 0;
319                    pos = mPendingMoves > 0 ? pos + mNumRows: pos - mNumRows) {
320                View v = findViewByPosition(pos);
321                if (v == null) {
322                    break;
323                }
324                if (!canScrollTo(v)) {
325                    continue;
326                }
327                newSelected = v;
328                mFocusPosition = pos;
329                mSubFocusPosition = 0;
330                if (mPendingMoves > 0) {
331                    mPendingMoves--;
332                } else {
333                    mPendingMoves++;
334                }
335            }
336            if (newSelected != null && hasFocus()) {
337                mInSelection = true;
338                newSelected.requestFocus();
339                mInSelection = false;
340            }
341        }
342
343        /**
344         * Called after laid out an item.  Staggered grid should find view on same
345         * Row and consume pending movements.
346         */
347        void consumePendingMovesAfterLayout() {
348            if (mStaggeredGrid && mPendingMoves != 0) {
349                // consume pending moves, focus to item on the same row.
350                mPendingMoves = processSelectionMoves(true, mPendingMoves);
351            }
352            if (mPendingMoves == 0 || (mPendingMoves > 0 && hasCreatedLastItem())
353                    || (mPendingMoves < 0 && hasCreatedFirstItem())) {
354                setTargetPosition(mFocusPosition);
355                stop();
356            }
357        }
358
359        @Override
360        protected void updateActionForInterimTarget(Action action) {
361            if (mPendingMoves == 0) {
362                return;
363            }
364            super.updateActionForInterimTarget(action);
365        }
366
367        @Override
368        public PointF computeScrollVectorForPosition(int targetPosition) {
369            if (mPendingMoves == 0) {
370                return null;
371            }
372            int direction = (mReverseFlowPrimary ? mPendingMoves > 0 : mPendingMoves < 0) ?
373                    -1 : 1;
374            if (mOrientation == HORIZONTAL) {
375                return new PointF(direction, 0);
376            } else {
377                return new PointF(0, direction);
378            }
379        }
380
381        @Override
382        protected void onStop() {
383            super.onStop();
384            // if we hit wall,  need clear the remaining pending moves.
385            mPendingMoves = 0;
386            mPendingMoveSmoothScroller = null;
387            View v = findViewByPosition(getTargetPosition());
388            if (v != null) scrollToView(v, true);
389        }
390    };
391
392    private static final String TAG = "GridLayoutManager";
393    private static final boolean DEBUG = false;
394    private static final boolean TRACE = false;
395
396    // maximum pending movement in one direction.
397    private final static int MAX_PENDING_MOVES = 10;
398    // minimal milliseconds to scroll window size in major direction,  we put a cap to prevent the
399    // effect smooth scrolling too over to bind an item view then drag the item view back.
400    private final static int MIN_MS_SMOOTH_SCROLL_MAIN_SCREEN = 30;
401
402    private String getTag() {
403        return TAG + ":" + mBaseGridView.getId();
404    }
405
406    private final BaseGridView mBaseGridView;
407
408    /**
409     * Note on conventions in the presence of RTL layout directions:
410     * Many properties and method names reference entities related to the
411     * beginnings and ends of things.  In the presence of RTL flows,
412     * it may not be clear whether this is intended to reference a
413     * quantity that changes direction in RTL cases, or a quantity that
414     * does not.  Here are the conventions in use:
415     *
416     * start/end: coordinate quantities - do reverse
417     * (optical) left/right: coordinate quantities - do not reverse
418     * low/high: coordinate quantities - do not reverse
419     * min/max: coordinate quantities - do not reverse
420     * scroll offset - coordinate quantities - do not reverse
421     * first/last: positional indices - do not reverse
422     * front/end: positional indices - do not reverse
423     * prepend/append: related to positional indices - do not reverse
424     *
425     * Note that although quantities do not reverse in RTL flows, their
426     * relationship does.  In LTR flows, the first positional index is
427     * leftmost; in RTL flows, it is rightmost.  Thus, anywhere that
428     * positional quantities are mapped onto coordinate quantities,
429     * the flow must be checked and the logic reversed.
430     */
431
432    /**
433     * The orientation of a "row".
434     */
435    private int mOrientation = HORIZONTAL;
436
437    private RecyclerView.State mState;
438    private RecyclerView.Recycler mRecycler;
439
440    private static final Rect sTempRect = new Rect();
441
442    private boolean mInLayout;
443    private boolean mInScroll;
444    private boolean mInFastRelayout;
445    /**
446     * During full layout pass, when GridView had focus: onLayoutChildren will
447     * skip non-focusable child and adjust mFocusPosition.
448     */
449    private boolean mInLayoutSearchFocus;
450    private boolean mInSelection = false;
451
452    private OnChildSelectedListener mChildSelectedListener = null;
453
454    private ArrayList<OnChildViewHolderSelectedListener> mChildViewHolderSelectedListeners = null;
455
456    private OnChildLaidOutListener mChildLaidOutListener = null;
457
458    /**
459     * The focused position, it's not the currently visually aligned position
460     * but it is the final position that we intend to focus on. If there are
461     * multiple setSelection() called, mFocusPosition saves last value.
462     */
463    private int mFocusPosition = NO_POSITION;
464
465    /**
466     * A view can have mutliple alignment position,  this is the index of which
467     * alignment is used,  by default is 0.
468     */
469    private int mSubFocusPosition = 0;
470
471    /**
472     * LinearSmoothScroller that consume pending DPAD movements.
473     */
474    private PendingMoveSmoothScroller mPendingMoveSmoothScroller;
475
476    /**
477     * The offset to be applied to mFocusPosition, due to adapter change, on the next
478     * layout.  Set to Integer.MIN_VALUE means we should stop adding delta to mFocusPosition
479     * until next layout cycler.
480     * TODO:  This is somewhat duplication of RecyclerView getOldPosition() which is
481     * unfortunately cleared after prelayout.
482     */
483    private int mFocusPositionOffset = 0;
484
485    /**
486     * Extra pixels applied on primary direction.
487     */
488    private int mPrimaryScrollExtra;
489
490    /**
491     * Force a full layout under certain situations.  E.g. Rows change, jump to invisible child.
492     */
493    private boolean mForceFullLayout;
494
495    /**
496     * True if layout is enabled.
497     */
498    private boolean mLayoutEnabled = true;
499
500    /**
501     * override child visibility
502     */
503    private int mChildVisibility = -1;
504
505    /**
506     * The scroll offsets of the viewport relative to the entire view.
507     */
508    private int mScrollOffsetPrimary;
509    private int mScrollOffsetSecondary;
510
511    /**
512     * User-specified row height/column width.  Can be WRAP_CONTENT.
513     */
514    private int mRowSizeSecondaryRequested;
515
516    /**
517     * The fixed size of each grid item in the secondary direction. This corresponds to
518     * the row height, equal for all rows. Grid items may have variable length
519     * in the primary direction.
520     */
521    private int mFixedRowSizeSecondary;
522
523    /**
524     * Tracks the secondary size of each row.
525     */
526    private int[] mRowSizeSecondary;
527
528    /**
529     * Flag controlling whether the current/next layout should
530     * be updating the secondary size of rows.
531     */
532    private boolean mRowSecondarySizeRefresh;
533
534    /**
535     * The maximum measured size of the view.
536     */
537    private int mMaxSizeSecondary;
538
539    /**
540     * Margin between items.
541     */
542    private int mHorizontalMargin;
543    /**
544     * Margin between items vertically.
545     */
546    private int mVerticalMargin;
547    /**
548     * Margin in main direction.
549     */
550    private int mMarginPrimary;
551    /**
552     * Margin in second direction.
553     */
554    private int mMarginSecondary;
555    /**
556     * How to position child in secondary direction.
557     */
558    private int mGravity = Gravity.START | Gravity.TOP;
559    /**
560     * The number of rows in the grid.
561     */
562    private int mNumRows;
563    /**
564     * Number of rows requested, can be 0 to be determined by parent size and
565     * rowHeight.
566     */
567    private int mNumRowsRequested = 1;
568
569    /**
570     * Saves grid information of each view.
571     */
572    Grid mGrid;
573
574    /**
575     * Focus Scroll strategy.
576     */
577    private int mFocusScrollStrategy = BaseGridView.FOCUS_SCROLL_ALIGNED;
578    /**
579     * Defines how item view is aligned in the window.
580     */
581    private final WindowAlignment mWindowAlignment = new WindowAlignment();
582
583    /**
584     * Defines how item view is aligned.
585     */
586    private final ItemAlignment mItemAlignment = new ItemAlignment();
587
588    /**
589     * Dimensions of the view, width or height depending on orientation.
590     */
591    private int mSizePrimary;
592
593    /**
594     * Pixels of extra space for layout item (outside the widget)
595     */
596    private int mExtraLayoutSpace;
597
598    /**
599     *  Allow DPAD key to navigate out at the front of the View (where position = 0),
600     *  default is false.
601     */
602    private boolean mFocusOutFront;
603
604    /**
605     * Allow DPAD key to navigate out at the end of the view, default is false.
606     */
607    private boolean mFocusOutEnd;
608
609    /**
610     *  Allow DPAD key to navigate out of second axis.
611     *  default is true.
612     */
613    private boolean mFocusOutSideStart = true;
614
615    /**
616     * Allow DPAD key to navigate out of second axis.
617     */
618    private boolean mFocusOutSideEnd = true;
619
620    /**
621     * True if focus search is disabled.
622     */
623    private boolean mFocusSearchDisabled;
624
625    /**
626     * True if prune child,  might be disabled during transition.
627     */
628    private boolean mPruneChild = true;
629
630    /**
631     * True if scroll content,  might be disabled during transition.
632     */
633    private boolean mScrollEnabled = true;
634
635    /**
636     * Temporary variable: an int array of length=2.
637     */
638    private static int[] sTwoInts = new int[2];
639
640    /**
641     * Set to true for RTL layout in horizontal orientation
642     */
643    private boolean mReverseFlowPrimary = false;
644
645    /**
646     * Set to true for RTL layout in vertical orientation
647     */
648    private boolean mReverseFlowSecondary = false;
649
650    /**
651     * Temporaries used for measuring.
652     */
653    private int[] mMeasuredDimension = new int[2];
654
655    final ViewsStateBundle mChildrenStates = new ViewsStateBundle();
656
657    /**
658     * Optional interface implemented by Adapter.
659     */
660    private FacetProviderAdapter mFacetProviderAdapter;
661
662    public GridLayoutManager(BaseGridView baseGridView) {
663        mBaseGridView = baseGridView;
664    }
665
666    public void setOrientation(int orientation) {
667        if (orientation != HORIZONTAL && orientation != VERTICAL) {
668            if (DEBUG) Log.v(getTag(), "invalid orientation: " + orientation);
669            return;
670        }
671
672        mOrientation = orientation;
673        mWindowAlignment.setOrientation(orientation);
674        mItemAlignment.setOrientation(orientation);
675        mForceFullLayout = true;
676    }
677
678    public void onRtlPropertiesChanged(int layoutDirection) {
679        if (mOrientation == HORIZONTAL) {
680            mReverseFlowPrimary = layoutDirection == View.LAYOUT_DIRECTION_RTL;
681            mReverseFlowSecondary = false;
682        } else {
683            mReverseFlowSecondary = layoutDirection == View.LAYOUT_DIRECTION_RTL;
684            mReverseFlowPrimary = false;
685        }
686        mWindowAlignment.horizontal.setReversedFlow(layoutDirection == View.LAYOUT_DIRECTION_RTL);
687    }
688
689    public int getFocusScrollStrategy() {
690        return mFocusScrollStrategy;
691    }
692
693    public void setFocusScrollStrategy(int focusScrollStrategy) {
694        mFocusScrollStrategy = focusScrollStrategy;
695    }
696
697    public void setWindowAlignment(int windowAlignment) {
698        mWindowAlignment.mainAxis().setWindowAlignment(windowAlignment);
699    }
700
701    public int getWindowAlignment() {
702        return mWindowAlignment.mainAxis().getWindowAlignment();
703    }
704
705    public void setWindowAlignmentOffset(int alignmentOffset) {
706        mWindowAlignment.mainAxis().setWindowAlignmentOffset(alignmentOffset);
707    }
708
709    public int getWindowAlignmentOffset() {
710        return mWindowAlignment.mainAxis().getWindowAlignmentOffset();
711    }
712
713    public void setWindowAlignmentOffsetPercent(float offsetPercent) {
714        mWindowAlignment.mainAxis().setWindowAlignmentOffsetPercent(offsetPercent);
715    }
716
717    public float getWindowAlignmentOffsetPercent() {
718        return mWindowAlignment.mainAxis().getWindowAlignmentOffsetPercent();
719    }
720
721    public void setItemAlignmentOffset(int alignmentOffset) {
722        mItemAlignment.mainAxis().setItemAlignmentOffset(alignmentOffset);
723        updateChildAlignments();
724    }
725
726    public int getItemAlignmentOffset() {
727        return mItemAlignment.mainAxis().getItemAlignmentOffset();
728    }
729
730    public void setItemAlignmentOffsetWithPadding(boolean withPadding) {
731        mItemAlignment.mainAxis().setItemAlignmentOffsetWithPadding(withPadding);
732        updateChildAlignments();
733    }
734
735    public boolean isItemAlignmentOffsetWithPadding() {
736        return mItemAlignment.mainAxis().isItemAlignmentOffsetWithPadding();
737    }
738
739    public void setItemAlignmentOffsetPercent(float offsetPercent) {
740        mItemAlignment.mainAxis().setItemAlignmentOffsetPercent(offsetPercent);
741        updateChildAlignments();
742    }
743
744    public float getItemAlignmentOffsetPercent() {
745        return mItemAlignment.mainAxis().getItemAlignmentOffsetPercent();
746    }
747
748    public void setItemAlignmentViewId(int viewId) {
749        mItemAlignment.mainAxis().setItemAlignmentViewId(viewId);
750        updateChildAlignments();
751    }
752
753    public int getItemAlignmentViewId() {
754        return mItemAlignment.mainAxis().getItemAlignmentViewId();
755    }
756
757    public void setFocusOutAllowed(boolean throughFront, boolean throughEnd) {
758        mFocusOutFront = throughFront;
759        mFocusOutEnd = throughEnd;
760    }
761
762    public void setFocusOutSideAllowed(boolean throughStart, boolean throughEnd) {
763        mFocusOutSideStart = throughStart;
764        mFocusOutSideEnd = throughEnd;
765    }
766
767    public void setNumRows(int numRows) {
768        if (numRows < 0) throw new IllegalArgumentException();
769        mNumRowsRequested = numRows;
770    }
771
772    /**
773     * Set the row height. May be WRAP_CONTENT, or a size in pixels.
774     */
775    public void setRowHeight(int height) {
776        if (height >= 0 || height == ViewGroup.LayoutParams.WRAP_CONTENT) {
777            mRowSizeSecondaryRequested = height;
778        } else {
779            throw new IllegalArgumentException("Invalid row height: " + height);
780        }
781    }
782
783    public void setItemMargin(int margin) {
784        mVerticalMargin = mHorizontalMargin = margin;
785        mMarginPrimary = mMarginSecondary = margin;
786    }
787
788    public void setVerticalMargin(int margin) {
789        if (mOrientation == HORIZONTAL) {
790            mMarginSecondary = mVerticalMargin = margin;
791        } else {
792            mMarginPrimary = mVerticalMargin = margin;
793        }
794    }
795
796    public void setHorizontalMargin(int margin) {
797        if (mOrientation == HORIZONTAL) {
798            mMarginPrimary = mHorizontalMargin = margin;
799        } else {
800            mMarginSecondary = mHorizontalMargin = margin;
801        }
802    }
803
804    public int getVerticalMargin() {
805        return mVerticalMargin;
806    }
807
808    public int getHorizontalMargin() {
809        return mHorizontalMargin;
810    }
811
812    public void setGravity(int gravity) {
813        mGravity = gravity;
814    }
815
816    protected boolean hasDoneFirstLayout() {
817        return mGrid != null;
818    }
819
820    public void setOnChildSelectedListener(OnChildSelectedListener listener) {
821        mChildSelectedListener = listener;
822    }
823
824    public void setOnChildViewHolderSelectedListener(OnChildViewHolderSelectedListener listener) {
825        if (listener == null) {
826            mChildViewHolderSelectedListeners = null;
827            return;
828        }
829        if (mChildViewHolderSelectedListeners == null) {
830            mChildViewHolderSelectedListeners = new ArrayList<OnChildViewHolderSelectedListener>();
831        } else {
832            mChildViewHolderSelectedListeners.clear();
833        }
834        mChildViewHolderSelectedListeners.add(listener);
835    }
836
837    public void addOnChildViewHolderSelectedListener(OnChildViewHolderSelectedListener listener) {
838        if (mChildViewHolderSelectedListeners == null) {
839            mChildViewHolderSelectedListeners = new ArrayList<OnChildViewHolderSelectedListener>();
840        }
841        mChildViewHolderSelectedListeners.add(listener);
842    }
843
844    public void removeOnChildViewHolderSelectedListener(OnChildViewHolderSelectedListener
845            listener) {
846        if (mChildViewHolderSelectedListeners != null) {
847            mChildViewHolderSelectedListeners.remove(listener);
848        }
849    }
850
851    boolean hasOnChildViewHolderSelectedListener() {
852        return mChildViewHolderSelectedListeners != null &&
853                mChildViewHolderSelectedListeners.size() > 0;
854    }
855
856    void fireOnChildViewHolderSelected(RecyclerView parent, RecyclerView.ViewHolder child,
857            int position, int subposition) {
858        if (mChildViewHolderSelectedListeners == null) {
859            return;
860        }
861        for (int i = mChildViewHolderSelectedListeners.size() - 1; i >= 0 ; i--) {
862            mChildViewHolderSelectedListeners.get(i).onChildViewHolderSelected(parent, child,
863                    position, subposition);
864        }
865    }
866
867    void setOnChildLaidOutListener(OnChildLaidOutListener listener) {
868        mChildLaidOutListener = listener;
869    }
870
871    private int getPositionByView(View view) {
872        if (view == null) {
873            return NO_POSITION;
874        }
875        LayoutParams params = (LayoutParams) view.getLayoutParams();
876        if (params == null || params.isItemRemoved()) {
877            // when item is removed, the position value can be any value.
878            return NO_POSITION;
879        }
880        return params.getViewPosition();
881    }
882
883    private int getSubPositionByView(View view, View childView) {
884        if (view == null || childView == null) {
885            return 0;
886        }
887        final LayoutParams lp = (LayoutParams) view.getLayoutParams();
888        final ItemAlignmentFacet facet = lp.getItemAlignmentFacet();
889        if (facet != null) {
890            final ItemAlignmentFacet.ItemAlignmentDef[] defs = facet.getAlignmentDefs();
891            if (defs.length > 1) {
892                while (childView != view) {
893                    int id = childView.getId();
894                    if (id != View.NO_ID) {
895                        for (int i = 1; i < defs.length; i++) {
896                            if (defs[i].getItemAlignmentFocusViewId() == id) {
897                                return i;
898                            }
899                        }
900                    }
901                    childView = (View) childView.getParent();
902                }
903            }
904        }
905        return 0;
906    }
907
908    private int getPositionByIndex(int index) {
909        return getPositionByView(getChildAt(index));
910    }
911
912    private void dispatchChildSelected() {
913        if (mChildSelectedListener == null && !hasOnChildViewHolderSelectedListener()) {
914            return;
915        }
916
917        if (TRACE) TraceHelper.beginSection("onChildSelected");
918        View view = mFocusPosition == NO_POSITION ? null : findViewByPosition(mFocusPosition);
919        if (view != null) {
920            RecyclerView.ViewHolder vh = mBaseGridView.getChildViewHolder(view);
921            if (mChildSelectedListener != null) {
922                mChildSelectedListener.onChildSelected(mBaseGridView, view, mFocusPosition,
923                        vh == null? NO_ID: vh.getItemId());
924            }
925            fireOnChildViewHolderSelected(mBaseGridView, vh, mFocusPosition, mSubFocusPosition);
926        } else {
927            if (mChildSelectedListener != null) {
928                mChildSelectedListener.onChildSelected(mBaseGridView, null, NO_POSITION, NO_ID);
929            }
930            fireOnChildViewHolderSelected(mBaseGridView, null, NO_POSITION, 0);
931        }
932        if (TRACE) TraceHelper.endSection();
933
934        // Children may request layout when a child selection event occurs (such as a change of
935        // padding on the current and previously selected rows).
936        // If in layout, a child requesting layout may have been laid out before the selection
937        // callback.
938        // If it was not, the child will be laid out after the selection callback.
939        // If so, the layout request will be honoured though the view system will emit a double-
940        // layout warning.
941        // If not in layout, we may be scrolling in which case the child layout request will be
942        // eaten by recyclerview.  Post a requestLayout.
943        if (!mInLayout && !mBaseGridView.isLayoutRequested()) {
944            int childCount = getChildCount();
945            for (int i = 0; i < childCount; i++) {
946                if (getChildAt(i).isLayoutRequested()) {
947                    forceRequestLayout();
948                    break;
949                }
950            }
951        }
952    }
953
954    @Override
955    public boolean canScrollHorizontally() {
956        // We can scroll horizontally if we have horizontal orientation, or if
957        // we are vertical and have more than one column.
958        return mOrientation == HORIZONTAL || mNumRows > 1;
959    }
960
961    @Override
962    public boolean canScrollVertically() {
963        // We can scroll vertically if we have vertical orientation, or if we
964        // are horizontal and have more than one row.
965        return mOrientation == VERTICAL || mNumRows > 1;
966    }
967
968    @Override
969    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
970        return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
971                ViewGroup.LayoutParams.WRAP_CONTENT);
972    }
973
974    @Override
975    public RecyclerView.LayoutParams generateLayoutParams(Context context, AttributeSet attrs) {
976        return new LayoutParams(context, attrs);
977    }
978
979    @Override
980    public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
981        if (lp instanceof LayoutParams) {
982            return new LayoutParams((LayoutParams) lp);
983        } else if (lp instanceof RecyclerView.LayoutParams) {
984            return new LayoutParams((RecyclerView.LayoutParams) lp);
985        } else if (lp instanceof MarginLayoutParams) {
986            return new LayoutParams((MarginLayoutParams) lp);
987        } else {
988            return new LayoutParams(lp);
989        }
990    }
991
992    protected View getViewForPosition(int position) {
993        return mRecycler.getViewForPosition(position);
994    }
995
996    final int getOpticalLeft(View v) {
997        return ((LayoutParams) v.getLayoutParams()).getOpticalLeft(v);
998    }
999
1000    final int getOpticalRight(View v) {
1001        return ((LayoutParams) v.getLayoutParams()).getOpticalRight(v);
1002    }
1003
1004    final int getOpticalTop(View v) {
1005        return ((LayoutParams) v.getLayoutParams()).getOpticalTop(v);
1006    }
1007
1008    final int getOpticalBottom(View v) {
1009        return ((LayoutParams) v.getLayoutParams()).getOpticalBottom(v);
1010    }
1011
1012    private int getViewMin(View v) {
1013        LayoutParams lp = (LayoutParams) v.getLayoutParams();
1014        return (mOrientation == HORIZONTAL) ? lp.getDecoratedOpticalLeftWithMargin(this, v)
1015                : lp.getDecoratedOpticalTopWithMargin(this, v);
1016    }
1017
1018    private int getViewMax(View v) {
1019        LayoutParams lp = (LayoutParams) v.getLayoutParams();
1020        return (mOrientation == HORIZONTAL) ? lp.getDecoratedOpticalRightWithMargin(this, v)
1021                : lp.getDecoratedOpticalBottomWithMargin(this, v);
1022    }
1023
1024    private int getViewPrimarySize(View view) {
1025        LayoutParams p = (LayoutParams) view.getLayoutParams();
1026        return mOrientation == HORIZONTAL ? p.getDecoratedOpticalWidthWithMargin(this, view)
1027                : p.getDecoratedOpticalHeightWithMargin(this, view);
1028    }
1029
1030    private int getViewCenter(View view) {
1031        return (mOrientation == HORIZONTAL) ? getViewCenterX(view) : getViewCenterY(view);
1032    }
1033
1034    private int getViewCenterSecondary(View view) {
1035        return (mOrientation == HORIZONTAL) ? getViewCenterY(view) : getViewCenterX(view);
1036    }
1037
1038    private int getViewCenterX(View v) {
1039        LayoutParams p = (LayoutParams) v.getLayoutParams();
1040        return p.getOpticalLeft(v) + p.getAlignX();
1041    }
1042
1043    private int getViewCenterY(View v) {
1044        LayoutParams p = (LayoutParams) v.getLayoutParams();
1045        return p.getOpticalTop(v) + p.getAlignY();
1046    }
1047
1048    /**
1049     * Save Recycler and State for convenience.  Must be paired with leaveContext().
1050     */
1051    private void saveContext(Recycler recycler, State state) {
1052        if (mRecycler != null || mState != null) {
1053            Log.e(TAG, "Recycler information was not released, bug!");
1054        }
1055        mRecycler = recycler;
1056        mState = state;
1057    }
1058
1059    /**
1060     * Discard saved Recycler and State.
1061     */
1062    private void leaveContext() {
1063        mRecycler = null;
1064        mState = null;
1065    }
1066
1067    /**
1068     * Re-initialize data structures for a data change or handling invisible
1069     * selection. The method tries its best to preserve position information so
1070     * that staggered grid looks same before and after re-initialize.
1071     * @return true if can fastRelayout()
1072     */
1073    private boolean layoutInit() {
1074        boolean focusViewWasInTree = mGrid != null && mFocusPosition >= 0
1075                && mFocusPosition >= mGrid.getFirstVisibleIndex()
1076                && mFocusPosition <= mGrid.getLastVisibleIndex();
1077        final int newItemCount = mState.getItemCount();
1078        if (newItemCount == 0) {
1079            mFocusPosition = NO_POSITION;
1080            mSubFocusPosition = 0;
1081        } else if (mFocusPosition >= newItemCount) {
1082            mFocusPosition = newItemCount - 1;
1083            mSubFocusPosition = 0;
1084        } else if (mFocusPosition == NO_POSITION && newItemCount > 0) {
1085            // if focus position is never set before,  initialize it to 0
1086            mFocusPosition = 0;
1087            mSubFocusPosition = 0;
1088        }
1089        if (!mState.didStructureChange() && mGrid.getFirstVisibleIndex() >= 0 &&
1090                !mForceFullLayout && mGrid != null && mGrid.getNumRows() == mNumRows) {
1091            updateScrollController();
1092            updateScrollSecondAxis();
1093            mGrid.setMargin(mMarginPrimary);
1094            if (!focusViewWasInTree && mFocusPosition != NO_POSITION) {
1095                mGrid.setStart(mFocusPosition);
1096            }
1097            return true;
1098        } else {
1099            mForceFullLayout = false;
1100            int firstVisibleIndex = focusViewWasInTree ? mGrid.getFirstVisibleIndex() : 0;
1101
1102            if (mGrid == null || mNumRows != mGrid.getNumRows() ||
1103                    mReverseFlowPrimary != mGrid.isReversedFlow()) {
1104                mGrid = Grid.createGrid(mNumRows);
1105                mGrid.setProvider(mGridProvider);
1106                mGrid.setReversedFlow(mReverseFlowPrimary);
1107            }
1108            initScrollController();
1109            updateScrollSecondAxis();
1110            mGrid.setMargin(mMarginPrimary);
1111            detachAndScrapAttachedViews(mRecycler);
1112            mGrid.resetVisibleIndex();
1113            if (mFocusPosition == NO_POSITION) {
1114                mBaseGridView.clearFocus();
1115            }
1116            mWindowAlignment.mainAxis().invalidateScrollMin();
1117            mWindowAlignment.mainAxis().invalidateScrollMax();
1118            if (focusViewWasInTree && firstVisibleIndex <= mFocusPosition) {
1119                // if focusView was in tree, we will add item from first visible item
1120                mGrid.setStart(firstVisibleIndex);
1121            } else {
1122                // if focusView was not in tree, it's probably because focus position jumped
1123                // far away from visible range,  so use mFocusPosition as start
1124                mGrid.setStart(mFocusPosition);
1125            }
1126            return false;
1127        }
1128    }
1129
1130    private int getRowSizeSecondary(int rowIndex) {
1131        if (mFixedRowSizeSecondary != 0) {
1132            return mFixedRowSizeSecondary;
1133        }
1134        if (mRowSizeSecondary == null) {
1135            return 0;
1136        }
1137        return mRowSizeSecondary[rowIndex];
1138    }
1139
1140    private int getRowStartSecondary(int rowIndex) {
1141        int start = 0;
1142        // Iterate from left to right, which is a different index traversal
1143        // in RTL flow
1144        if (mReverseFlowSecondary) {
1145            for (int i = mNumRows-1; i > rowIndex; i--) {
1146                start += getRowSizeSecondary(i) + mMarginSecondary;
1147            }
1148        } else {
1149            for (int i = 0; i < rowIndex; i++) {
1150                start += getRowSizeSecondary(i) + mMarginSecondary;
1151            }
1152        }
1153        return start;
1154    }
1155
1156    private int getSizeSecondary() {
1157        int rightmostIndex = mReverseFlowSecondary ? 0 : mNumRows - 1;
1158        return getRowStartSecondary(rightmostIndex) + getRowSizeSecondary(rightmostIndex);
1159    }
1160
1161    int getDecoratedMeasuredWidthWithMargin(View v) {
1162        final LayoutParams lp = (LayoutParams) v.getLayoutParams();
1163        return getDecoratedMeasuredWidth(v) + lp.leftMargin + lp.rightMargin;
1164    }
1165
1166    int getDecoratedMeasuredHeightWithMargin(View v) {
1167        final LayoutParams lp = (LayoutParams) v.getLayoutParams();
1168        return getDecoratedMeasuredHeight(v) + lp.topMargin + lp.bottomMargin;
1169    }
1170
1171    private void measureScrapChild(int position, int widthSpec, int heightSpec,
1172            int[] measuredDimension) {
1173        View view = mRecycler.getViewForPosition(position);
1174        if (view != null) {
1175            final LayoutParams p = (LayoutParams) view.getLayoutParams();
1176            calculateItemDecorationsForChild(view, sTempRect);
1177            int widthUsed = p.leftMargin + p.rightMargin + sTempRect.left + sTempRect.right;
1178            int heightUsed = p.topMargin + p.bottomMargin + sTempRect.top + sTempRect.bottom;
1179
1180            int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
1181                    getPaddingLeft() + getPaddingRight() + widthUsed, p.width);
1182            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
1183                    getPaddingTop() + getPaddingBottom() + heightUsed, p.height);
1184            view.measure(childWidthSpec, childHeightSpec);
1185
1186            measuredDimension[0] = getDecoratedMeasuredWidthWithMargin(view);
1187            measuredDimension[1] = getDecoratedMeasuredHeightWithMargin(view);
1188            mRecycler.recycleView(view);
1189        }
1190    }
1191
1192    private boolean processRowSizeSecondary(boolean measure) {
1193        if (mFixedRowSizeSecondary != 0 || mRowSizeSecondary == null) {
1194            return false;
1195        }
1196
1197        if (TRACE) TraceHelper.beginSection("processRowSizeSecondary");
1198        CircularIntArray[] rows = mGrid == null ? null : mGrid.getItemPositionsInRows();
1199        boolean changed = false;
1200        int scrapChildWidth = -1;
1201        int scrapChildHeight = -1;
1202
1203        for (int rowIndex = 0; rowIndex < mNumRows; rowIndex++) {
1204            CircularIntArray row = rows == null ? null : rows[rowIndex];
1205            final int rowItemsPairCount = row == null ? 0 : row.size();
1206            int rowSize = -1;
1207            for (int rowItemPairIndex = 0; rowItemPairIndex < rowItemsPairCount;
1208                    rowItemPairIndex += 2) {
1209                final int rowIndexStart = row.get(rowItemPairIndex);
1210                final int rowIndexEnd = row.get(rowItemPairIndex + 1);
1211                for (int i = rowIndexStart; i <= rowIndexEnd; i++) {
1212                    final View view = findViewByPosition(i);
1213                    if (view == null) {
1214                        continue;
1215                    }
1216                    if (measure) {
1217                        measureChild(view);
1218                    }
1219                    final int secondarySize = mOrientation == HORIZONTAL ?
1220                            getDecoratedMeasuredHeightWithMargin(view)
1221                            : getDecoratedMeasuredWidthWithMargin(view);
1222                    if (secondarySize > rowSize) {
1223                        rowSize = secondarySize;
1224                    }
1225                }
1226            }
1227
1228            final int itemCount = mState.getItemCount();
1229            if (!mBaseGridView.hasFixedSize() && measure && rowSize < 0 && itemCount > 0) {
1230                if (scrapChildWidth < 0 && scrapChildHeight < 0) {
1231                    int position;
1232                    if (mFocusPosition == NO_POSITION) {
1233                        position = 0;
1234                    } else if (mFocusPosition >= itemCount) {
1235                        position = itemCount - 1;
1236                    } else {
1237                        position = mFocusPosition;
1238                    }
1239                    measureScrapChild(position,
1240                            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
1241                            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
1242                            mMeasuredDimension);
1243                    scrapChildWidth = mMeasuredDimension[0];
1244                    scrapChildHeight = mMeasuredDimension[1];
1245                    if (DEBUG) Log.v(TAG, "measured scrap child: " + scrapChildWidth +
1246                            " " + scrapChildHeight);
1247                }
1248                rowSize = mOrientation == HORIZONTAL ? scrapChildHeight : scrapChildWidth;
1249            }
1250            if (rowSize < 0) {
1251                rowSize = 0;
1252            }
1253            if (mRowSizeSecondary[rowIndex] != rowSize) {
1254                if (DEBUG) Log.v(getTag(), "row size secondary changed: " + mRowSizeSecondary[rowIndex] +
1255                        ", " + rowSize);
1256                mRowSizeSecondary[rowIndex] = rowSize;
1257                changed = true;
1258            }
1259        }
1260
1261        if (TRACE) TraceHelper.endSection();
1262        return changed;
1263    }
1264
1265    /**
1266     * Checks if we need to update row secondary sizes.
1267     */
1268    private void updateRowSecondarySizeRefresh() {
1269        mRowSecondarySizeRefresh = processRowSizeSecondary(false);
1270        if (mRowSecondarySizeRefresh) {
1271            if (DEBUG) Log.v(getTag(), "mRowSecondarySizeRefresh now set");
1272            forceRequestLayout();
1273        }
1274    }
1275
1276    private void forceRequestLayout() {
1277        if (DEBUG) Log.v(getTag(), "forceRequestLayout");
1278        // RecyclerView prevents us from requesting layout in many cases
1279        // (during layout, during scroll, etc.)
1280        // For secondary row size wrap_content support we currently need a
1281        // second layout pass to update the measured size after having measured
1282        // and added child views in layoutChildren.
1283        // Force the second layout by posting a delayed runnable.
1284        // TODO: investigate allowing a second layout pass,
1285        // or move child add/measure logic to the measure phase.
1286        ViewCompat.postOnAnimation(mBaseGridView, mRequestLayoutRunnable);
1287    }
1288
1289    private final Runnable mRequestLayoutRunnable = new Runnable() {
1290        @Override
1291        public void run() {
1292            if (DEBUG) Log.v(getTag(), "request Layout from runnable");
1293            requestLayout();
1294        }
1295     };
1296
1297    @Override
1298    public void onMeasure(Recycler recycler, State state, int widthSpec, int heightSpec) {
1299        saveContext(recycler, state);
1300
1301        int sizePrimary, sizeSecondary, modeSecondary, paddingSecondary;
1302        int measuredSizeSecondary;
1303        if (mOrientation == HORIZONTAL) {
1304            sizePrimary = MeasureSpec.getSize(widthSpec);
1305            sizeSecondary = MeasureSpec.getSize(heightSpec);
1306            modeSecondary = MeasureSpec.getMode(heightSpec);
1307            paddingSecondary = getPaddingTop() + getPaddingBottom();
1308        } else {
1309            sizeSecondary = MeasureSpec.getSize(widthSpec);
1310            sizePrimary = MeasureSpec.getSize(heightSpec);
1311            modeSecondary = MeasureSpec.getMode(widthSpec);
1312            paddingSecondary = getPaddingLeft() + getPaddingRight();
1313        }
1314        if (DEBUG) Log.v(getTag(), "onMeasure widthSpec " + Integer.toHexString(widthSpec) +
1315                " heightSpec " + Integer.toHexString(heightSpec) +
1316                " modeSecondary " + Integer.toHexString(modeSecondary) +
1317                " sizeSecondary " + sizeSecondary + " " + this);
1318
1319        mMaxSizeSecondary = sizeSecondary;
1320
1321        if (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) {
1322            mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested;
1323            mFixedRowSizeSecondary = 0;
1324
1325            if (mRowSizeSecondary == null || mRowSizeSecondary.length != mNumRows) {
1326                mRowSizeSecondary = new int[mNumRows];
1327            }
1328
1329            // Measure all current children and update cached row heights
1330            processRowSizeSecondary(true);
1331
1332            switch (modeSecondary) {
1333            case MeasureSpec.UNSPECIFIED:
1334                measuredSizeSecondary = getSizeSecondary() + paddingSecondary;
1335                break;
1336            case MeasureSpec.AT_MOST:
1337                measuredSizeSecondary = Math.min(getSizeSecondary() + paddingSecondary,
1338                        mMaxSizeSecondary);
1339                break;
1340            case MeasureSpec.EXACTLY:
1341                measuredSizeSecondary = mMaxSizeSecondary;
1342                break;
1343            default:
1344                throw new IllegalStateException("wrong spec");
1345            }
1346
1347        } else {
1348            switch (modeSecondary) {
1349            case MeasureSpec.UNSPECIFIED:
1350                mFixedRowSizeSecondary = mRowSizeSecondaryRequested == 0 ?
1351                        sizeSecondary - paddingSecondary: mRowSizeSecondaryRequested;
1352                mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested;
1353                measuredSizeSecondary = mFixedRowSizeSecondary * mNumRows + mMarginSecondary
1354                    * (mNumRows - 1) + paddingSecondary;
1355                break;
1356            case MeasureSpec.AT_MOST:
1357            case MeasureSpec.EXACTLY:
1358                if (mNumRowsRequested == 0 && mRowSizeSecondaryRequested == 0) {
1359                    mNumRows = 1;
1360                    mFixedRowSizeSecondary = sizeSecondary - paddingSecondary;
1361                } else if (mNumRowsRequested == 0) {
1362                    mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
1363                    mNumRows = (sizeSecondary + mMarginSecondary)
1364                        / (mRowSizeSecondaryRequested + mMarginSecondary);
1365                } else if (mRowSizeSecondaryRequested == 0) {
1366                    mNumRows = mNumRowsRequested;
1367                    mFixedRowSizeSecondary = (sizeSecondary - paddingSecondary - mMarginSecondary
1368                            * (mNumRows - 1)) / mNumRows;
1369                } else {
1370                    mNumRows = mNumRowsRequested;
1371                    mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
1372                }
1373                measuredSizeSecondary = sizeSecondary;
1374                if (modeSecondary == MeasureSpec.AT_MOST) {
1375                    int childrenSize = mFixedRowSizeSecondary * mNumRows + mMarginSecondary
1376                        * (mNumRows - 1) + paddingSecondary;
1377                    if (childrenSize < measuredSizeSecondary) {
1378                        measuredSizeSecondary = childrenSize;
1379                    }
1380                }
1381                break;
1382            default:
1383                throw new IllegalStateException("wrong spec");
1384            }
1385        }
1386        if (mOrientation == HORIZONTAL) {
1387            setMeasuredDimension(sizePrimary, measuredSizeSecondary);
1388        } else {
1389            setMeasuredDimension(measuredSizeSecondary, sizePrimary);
1390        }
1391        if (DEBUG) {
1392            Log.v(getTag(), "onMeasure sizePrimary " + sizePrimary +
1393                    " measuredSizeSecondary " + measuredSizeSecondary +
1394                    " mFixedRowSizeSecondary " + mFixedRowSizeSecondary +
1395                    " mNumRows " + mNumRows);
1396        }
1397        leaveContext();
1398    }
1399
1400    private void measureChild(View child) {
1401        if (TRACE) TraceHelper.beginSection("measureChild");
1402        final LayoutParams lp = (LayoutParams) child.getLayoutParams();
1403        calculateItemDecorationsForChild(child, sTempRect);
1404        int widthUsed = lp.leftMargin + lp.rightMargin + sTempRect.left + sTempRect.right;
1405        int heightUsed = lp.topMargin + lp.bottomMargin + sTempRect.top + sTempRect.bottom;
1406
1407        final int secondarySpec = (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) ?
1408                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) :
1409                MeasureSpec.makeMeasureSpec(mFixedRowSizeSecondary, MeasureSpec.EXACTLY);
1410        int widthSpec, heightSpec;
1411
1412        if (mOrientation == HORIZONTAL) {
1413            widthSpec = ViewGroup.getChildMeasureSpec(
1414                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), widthUsed, lp.width);
1415            heightSpec = ViewGroup.getChildMeasureSpec(secondarySpec, heightUsed, lp.height);
1416        } else {
1417            heightSpec = ViewGroup.getChildMeasureSpec(
1418                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), heightUsed, lp.height);
1419            widthSpec = ViewGroup.getChildMeasureSpec(secondarySpec, widthUsed, lp.width);
1420        }
1421        child.measure(widthSpec, heightSpec);
1422        if (DEBUG) Log.v(getTag(), "measureChild secondarySpec " + Integer.toHexString(secondarySpec) +
1423                " widthSpec " + Integer.toHexString(widthSpec) +
1424                " heightSpec " + Integer.toHexString(heightSpec) +
1425                " measuredWidth " + child.getMeasuredWidth() +
1426                " measuredHeight " + child.getMeasuredHeight());
1427        if (DEBUG) Log.v(getTag(), "child lp width " + lp.width + " height " + lp.height);
1428        if (TRACE) TraceHelper.endSection();
1429    }
1430
1431    /**
1432     * Get facet from the ViewHolder or the viewType.
1433     */
1434    private <E> E getFacet(RecyclerView.ViewHolder vh, Class<? extends E> facetClass) {
1435        E facet = null;
1436        if (vh instanceof FacetProvider) {
1437            facet = (E) ((FacetProvider) vh).getFacet(facetClass);
1438        }
1439        if (facet == null && mFacetProviderAdapter != null) {
1440            FacetProvider p = mFacetProviderAdapter.getFacetProvider(vh.getItemViewType());
1441            if (p != null) {
1442                facet = (E) p.getFacet(facetClass);
1443            }
1444        }
1445        return facet;
1446    }
1447
1448    private Grid.Provider mGridProvider = new Grid.Provider() {
1449
1450        @Override
1451        public int getCount() {
1452            return mState.getItemCount();
1453        }
1454
1455        @Override
1456        public int createItem(int index, boolean append, Object[] item) {
1457            if (TRACE) TraceHelper.beginSection("createItem");
1458            if (TRACE) TraceHelper.beginSection("getview");
1459            View v = getViewForPosition(index);
1460            if (TRACE) TraceHelper.endSection();
1461            LayoutParams lp = (LayoutParams) v.getLayoutParams();
1462            RecyclerView.ViewHolder vh = mBaseGridView.getChildViewHolder(v);
1463            lp.setItemAlignmentFacet((ItemAlignmentFacet)getFacet(vh, ItemAlignmentFacet.class));
1464            // See recyclerView docs:  we don't need re-add scraped view if it was removed.
1465            if (!lp.isItemRemoved()) {
1466                if (TRACE) TraceHelper.beginSection("addView");
1467                if (append) {
1468                    addView(v);
1469                } else {
1470                    addView(v, 0);
1471                }
1472                if (TRACE) TraceHelper.endSection();
1473                if (mChildVisibility != -1) {
1474                    v.setVisibility(mChildVisibility);
1475                }
1476
1477                if (mPendingMoveSmoothScroller != null) {
1478                    mPendingMoveSmoothScroller.consumePendingMovesBeforeLayout();
1479                }
1480                int subindex = getSubPositionByView(v, v.findFocus());
1481                if (!mInLayout) {
1482                    // when we are appending item during scroll pass and the item's position
1483                    // matches the mFocusPosition,  we should signal a childSelected event.
1484                    // However if we are still running PendingMoveSmoothScroller,  we defer and
1485                    // signal the event in PendingMoveSmoothScroller.onStop().  This can
1486                    // avoid lots of childSelected events during a long smooth scrolling and
1487                    // increase performance.
1488                    if (index == mFocusPosition && subindex == mSubFocusPosition
1489                            && mPendingMoveSmoothScroller == null) {
1490                        dispatchChildSelected();
1491                    }
1492                } else if (!mInFastRelayout) {
1493                    // fastRelayout will dispatch event at end of onLayoutChildren().
1494                    // For full layout, two situations here:
1495                    // 1. mInLayoutSearchFocus is false, dispatchChildSelected() at mFocusPosition.
1496                    // 2. mInLayoutSearchFocus is true:  dispatchChildSelected() on first child
1497                    //    equal to or after mFocusPosition that can take focus.
1498                    if (!mInLayoutSearchFocus && index == mFocusPosition
1499                            && subindex == mSubFocusPosition) {
1500                        dispatchChildSelected();
1501                    } else if (mInLayoutSearchFocus && index >= mFocusPosition
1502                            && v.hasFocusable()) {
1503                        mFocusPosition = index;
1504                        mSubFocusPosition = subindex;
1505                        mInLayoutSearchFocus = false;
1506                        dispatchChildSelected();
1507                    }
1508                }
1509                measureChild(v);
1510            }
1511            item[0] = v;
1512            return mOrientation == HORIZONTAL ? getDecoratedMeasuredWidthWithMargin(v)
1513                    : getDecoratedMeasuredHeightWithMargin(v);
1514        }
1515
1516        @Override
1517        public void addItem(Object item, int index, int length, int rowIndex, int edge) {
1518            View v = (View) item;
1519            int start, end;
1520            if (edge == Integer.MIN_VALUE || edge == Integer.MAX_VALUE) {
1521                edge = !mGrid.isReversedFlow() ? mWindowAlignment.mainAxis().getPaddingLow()
1522                        : mWindowAlignment.mainAxis().getSize()
1523                                - mWindowAlignment.mainAxis().getPaddingHigh();
1524            }
1525            boolean edgeIsMin = !mGrid.isReversedFlow();
1526            if (edgeIsMin) {
1527                start = edge;
1528                end = edge + length;
1529            } else {
1530                start = edge - length;
1531                end = edge;
1532            }
1533            int startSecondary = getRowStartSecondary(rowIndex) - mScrollOffsetSecondary;
1534            mChildrenStates.loadView(v, index);
1535            layoutChild(rowIndex, v, start, end, startSecondary);
1536            if (DEBUG) {
1537                Log.d(getTag(), "addView " + index + " " + v);
1538            }
1539            if (TRACE) TraceHelper.endSection();
1540
1541            if (index == mGrid.getFirstVisibleIndex()) {
1542                if (!mGrid.isReversedFlow()) {
1543                    updateScrollMin();
1544                } else {
1545                    updateScrollMax();
1546                }
1547            }
1548            if (index == mGrid.getLastVisibleIndex()) {
1549                if (!mGrid.isReversedFlow()) {
1550                    updateScrollMax();
1551                } else {
1552                    updateScrollMin();
1553                }
1554            }
1555            if (!mInLayout && mPendingMoveSmoothScroller != null) {
1556                mPendingMoveSmoothScroller.consumePendingMovesAfterLayout();
1557            }
1558            if (mChildLaidOutListener != null) {
1559                RecyclerView.ViewHolder vh = mBaseGridView.getChildViewHolder(v);
1560                mChildLaidOutListener.onChildLaidOut(mBaseGridView, v, index,
1561                        vh == null ? NO_ID : vh.getItemId());
1562            }
1563        }
1564
1565        @Override
1566        public void removeItem(int index) {
1567            if (TRACE) TraceHelper.beginSection("removeItem");
1568            View v = findViewByPosition(index);
1569            if (mInLayout) {
1570                detachAndScrapView(v, mRecycler);
1571            } else {
1572                removeAndRecycleView(v, mRecycler);
1573            }
1574            if (TRACE) TraceHelper.endSection();
1575        }
1576
1577        @Override
1578        public int getEdge(int index) {
1579            if (mReverseFlowPrimary) {
1580                return getViewMax(findViewByPosition(index));
1581            } else {
1582                return getViewMin(findViewByPosition(index));
1583            }
1584        }
1585
1586        @Override
1587        public int getSize(int index) {
1588            return getViewPrimarySize(findViewByPosition(index));
1589        }
1590    };
1591
1592    private void layoutChild(int rowIndex, View v, int start, int end, int startSecondary) {
1593        if (TRACE) TraceHelper.beginSection("layoutChild");
1594        int sizeSecondary = mOrientation == HORIZONTAL ? getDecoratedMeasuredHeightWithMargin(v)
1595                : getDecoratedMeasuredWidthWithMargin(v);
1596        if (mFixedRowSizeSecondary > 0) {
1597            sizeSecondary = Math.min(sizeSecondary, mFixedRowSizeSecondary);
1598        }
1599        final int verticalGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
1600        final int horizontalGravity = (mReverseFlowPrimary || mReverseFlowSecondary) ?
1601                Gravity.getAbsoluteGravity(mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK, View.LAYOUT_DIRECTION_RTL) :
1602                mGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
1603        if (mOrientation == HORIZONTAL && verticalGravity == Gravity.TOP
1604                || mOrientation == VERTICAL && horizontalGravity == Gravity.LEFT) {
1605            // do nothing
1606        } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.BOTTOM
1607                || mOrientation == VERTICAL && horizontalGravity == Gravity.RIGHT) {
1608            startSecondary += getRowSizeSecondary(rowIndex) - sizeSecondary;
1609        } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.CENTER_VERTICAL
1610                || mOrientation == VERTICAL && horizontalGravity == Gravity.CENTER_HORIZONTAL) {
1611            startSecondary += (getRowSizeSecondary(rowIndex) - sizeSecondary) / 2;
1612        }
1613        int left, top, right, bottom;
1614        if (mOrientation == HORIZONTAL) {
1615            left = start;
1616            top = startSecondary;
1617            right = end;
1618            bottom = startSecondary + sizeSecondary;
1619        } else {
1620            top = start;
1621            left = startSecondary;
1622            bottom = end;
1623            right = startSecondary + sizeSecondary;
1624        }
1625        LayoutParams params = (LayoutParams) v.getLayoutParams();
1626        // layoutDecorated() doesn't handle margins, so we need exclude margin:
1627        int decoratedLeftExcludeMargin = left + params.leftMargin;
1628        int decoratedTopExcludeMargin = top + params.topMargin;
1629        int decoratedRightExcludeMargin = right - params.rightMargin;
1630        int decoratedBottomExcludeMargin = bottom - params.bottomMargin;
1631        layoutDecorated(v, decoratedLeftExcludeMargin, decoratedTopExcludeMargin,
1632                decoratedRightExcludeMargin, decoratedBottomExcludeMargin);
1633        // Now v.getLeft() includes the extra space for optical bounds, subtracting it from value
1634        // passed in layoutDecorated(), we can get the optical bounds insets.
1635        params.setOpticalInsets(decoratedLeftExcludeMargin - getDecoratedLeft(v),
1636                decoratedTopExcludeMargin - getDecoratedTop(v),
1637                getDecoratedRight(v) - decoratedRightExcludeMargin,
1638                getDecoratedBottom(v) - decoratedBottomExcludeMargin);
1639        updateChildAlignments(v);
1640        if (TRACE) TraceHelper.endSection();
1641    }
1642
1643    private void updateChildAlignments(View v) {
1644        final LayoutParams p = (LayoutParams) v.getLayoutParams();
1645        if (p.getItemAlignmentFacet() == null) {
1646            // Fallback to global settings on grid view
1647            p.setAlignX(mItemAlignment.horizontal.getAlignmentPosition(v));
1648            p.setAlignY(mItemAlignment.vertical.getAlignmentPosition(v));
1649        } else {
1650            // Use ItemAlignmentFacet defined on specific ViewHolder
1651            p.calculateItemAlignments(mOrientation, v);
1652            if (mOrientation == HORIZONTAL) {
1653                p.setAlignY(mItemAlignment.vertical.getAlignmentPosition(v));
1654            } else {
1655                p.setAlignX(mItemAlignment.horizontal.getAlignmentPosition(v));
1656            }
1657        }
1658    }
1659
1660    private void updateChildAlignments() {
1661        for (int i = 0, c = getChildCount(); i < c; i++) {
1662            updateChildAlignments(getChildAt(i));
1663        }
1664    }
1665
1666    void setExtraLayoutSpace(int extraLayoutSpace) {
1667        if (mExtraLayoutSpace == extraLayoutSpace) {
1668            return;
1669        } else if (mExtraLayoutSpace < 0) {
1670            throw new IllegalArgumentException("ExtraLayoutSpace must >= 0");
1671        }
1672        mExtraLayoutSpace = extraLayoutSpace;
1673        requestLayout();
1674    }
1675
1676    int getExtraLayoutSpace() {
1677        return mExtraLayoutSpace;
1678    }
1679
1680    private void removeInvisibleViewsAtEnd() {
1681        if (mPruneChild) {
1682            mGrid.removeInvisibleItemsAtEnd(mFocusPosition,
1683                    mReverseFlowPrimary ? -mExtraLayoutSpace : mSizePrimary + mExtraLayoutSpace);
1684        }
1685    }
1686
1687    private void removeInvisibleViewsAtFront() {
1688        if (mPruneChild) {
1689            mGrid.removeInvisibleItemsAtFront(mFocusPosition,
1690                    mReverseFlowPrimary ? mSizePrimary + mExtraLayoutSpace: -mExtraLayoutSpace);
1691        }
1692    }
1693
1694    private boolean appendOneColumnVisibleItems() {
1695        return mGrid.appendOneColumnVisibleItems();
1696    }
1697
1698    private boolean prependOneColumnVisibleItems() {
1699        return mGrid.prependOneColumnVisibleItems();
1700    }
1701
1702    private void appendVisibleItems() {
1703        mGrid.appendVisibleItems(mReverseFlowPrimary ? -mExtraLayoutSpace
1704                : mSizePrimary + mExtraLayoutSpace);
1705    }
1706
1707    private void prependVisibleItems() {
1708        mGrid.prependVisibleItems(mReverseFlowPrimary ? mSizePrimary + mExtraLayoutSpace
1709                : -mExtraLayoutSpace);
1710    }
1711
1712    /**
1713     * Fast layout when there is no structure change, adapter change, etc.
1714     * It will layout all views was layout requested or updated, until hit a view
1715     * with different size,  then it break and detachAndScrap all views after that.
1716     */
1717    private void fastRelayout() {
1718        boolean invalidateAfter = false;
1719        final int childCount = getChildCount();
1720        int position = -1;
1721        for (int index = 0; index < childCount; index++) {
1722            View view = getChildAt(index);
1723            position = getPositionByIndex(index);
1724            Grid.Location location = mGrid.getLocation(position);
1725            if (location == null) {
1726                if (DEBUG) Log.w(getTag(), "fastRelayout(): no Location at " + position);
1727                invalidateAfter = true;
1728                break;
1729            }
1730
1731            int startSecondary = getRowStartSecondary(location.row) - mScrollOffsetSecondary;
1732            int primarySize, end;
1733            int start = getViewMin(view);
1734            int oldPrimarySize = getViewPrimarySize(view);
1735
1736            LayoutParams lp = (LayoutParams) view.getLayoutParams();
1737            if (lp.viewNeedsUpdate()) {
1738                int viewIndex = mBaseGridView.indexOfChild(view);
1739                detachAndScrapView(view, mRecycler);
1740                view = getViewForPosition(position);
1741                addView(view, viewIndex);
1742            }
1743
1744            measureChild(view);
1745            if (mOrientation == HORIZONTAL) {
1746                primarySize = getDecoratedMeasuredWidthWithMargin(view);
1747                end = start + primarySize;
1748            } else {
1749                primarySize = getDecoratedMeasuredHeightWithMargin(view);
1750                end = start + primarySize;
1751            }
1752            layoutChild(location.row, view, start, end, startSecondary);
1753            if (oldPrimarySize != primarySize) {
1754                // size changed invalidate remaining Locations
1755                if (DEBUG) Log.d(getTag(), "fastRelayout: view size changed at " + position);
1756                invalidateAfter = true;
1757                break;
1758            }
1759        }
1760        if (invalidateAfter) {
1761            final int savedLastPos = mGrid.getLastVisibleIndex();
1762            mGrid.invalidateItemsAfter(position);
1763            if (mPruneChild) {
1764                // in regular prune child mode, we just append items up to edge limit
1765                appendVisibleItems();
1766                if (mFocusPosition >= 0 && mFocusPosition <= savedLastPos) {
1767                    // make sure add focus view back:  the view might be outside edge limit
1768                    // when there is delta in onLayoutChildren().
1769                    while (mGrid.getLastVisibleIndex() < mFocusPosition) {
1770                        mGrid.appendOneColumnVisibleItems();
1771                    }
1772                }
1773            } else {
1774                // prune disabled(e.g. in RowsFragment transition): append all removed items
1775                while (mGrid.appendOneColumnVisibleItems()
1776                        && mGrid.getLastVisibleIndex() < savedLastPos);
1777            }
1778        }
1779        updateScrollMin();
1780        updateScrollMax();
1781        updateScrollSecondAxis();
1782    }
1783
1784    public void removeAndRecycleAllViews(RecyclerView.Recycler recycler) {
1785        if (TRACE) TraceHelper.beginSection("removeAndRecycleAllViews");
1786        if (DEBUG) Log.v(TAG, "removeAndRecycleAllViews " + getChildCount());
1787        for (int i = getChildCount() - 1; i >= 0; i--) {
1788            removeAndRecycleViewAt(i, recycler);
1789        }
1790        if (TRACE) TraceHelper.endSection();
1791    }
1792
1793    // Lays out items based on the current scroll position
1794    @Override
1795    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
1796        if (DEBUG) {
1797            Log.v(getTag(), "layoutChildren start numRows " + mNumRows + " mScrollOffsetSecondary "
1798                    + mScrollOffsetSecondary + " mScrollOffsetPrimary " + mScrollOffsetPrimary
1799                    + " inPreLayout " + state.isPreLayout()
1800                    + " didStructureChange " + state.didStructureChange()
1801                    + " mForceFullLayout " + mForceFullLayout);
1802            Log.v(getTag(), "width " + getWidth() + " height " + getHeight());
1803        }
1804
1805        if (mNumRows == 0) {
1806            // haven't done measure yet
1807            return;
1808        }
1809        final int itemCount = state.getItemCount();
1810        if (itemCount < 0) {
1811            return;
1812        }
1813
1814        if (!mLayoutEnabled) {
1815            discardLayoutInfo();
1816            removeAndRecycleAllViews(recycler);
1817            return;
1818        }
1819        mInLayout = true;
1820
1821        if (state.didStructureChange()) {
1822            // didStructureChange() == true means attached item has been removed/added.
1823            // scroll animation: we are unable to continue a scroll animation,
1824            //    kill the scroll animation,  and let ItemAnimation move the item to new position.
1825            // position smooth scroller: kill the animation and stop at final position.
1826            // pending smooth scroller: stop and scroll to current focus position.
1827            mBaseGridView.stopScroll();
1828        }
1829        final boolean scrollToFocus = !isSmoothScrolling()
1830                && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED;
1831        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
1832            mFocusPosition = mFocusPosition + mFocusPositionOffset;
1833            mSubFocusPosition = 0;
1834        }
1835        mFocusPositionOffset = 0;
1836        saveContext(recycler, state);
1837
1838        View savedFocusView = findViewByPosition(mFocusPosition);
1839        int savedFocusPos = mFocusPosition;
1840        int savedSubFocusPos = mSubFocusPosition;
1841        boolean hadFocus = mBaseGridView.hasFocus();
1842
1843        // Track the old focus view so we can adjust our system scroll position
1844        // so that any scroll animations happening now will remain valid.
1845        // We must use same delta in Pre Layout (if prelayout exists) and second layout.
1846        // So we cache the deltas in PreLayout and use it in second layout.
1847        int delta = 0, deltaSecondary = 0;
1848        if (mFocusPosition != NO_POSITION && scrollToFocus
1849                && mBaseGridView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) {
1850            // FIXME: we should get the remaining scroll animation offset from RecyclerView
1851            if (savedFocusView != null) {
1852                if (getScrollPosition(savedFocusView, savedFocusView.findFocus(), sTwoInts)) {
1853                    delta = sTwoInts[0];
1854                    deltaSecondary = sTwoInts[1];
1855                }
1856            }
1857        }
1858
1859        if (mInFastRelayout = layoutInit()) {
1860            fastRelayout();
1861            // appends items till focus position.
1862            if (mFocusPosition != NO_POSITION) {
1863                View focusView = findViewByPosition(mFocusPosition);
1864                if (focusView != null) {
1865                    if (scrollToFocus) {
1866                        scrollToView(focusView, false);
1867                    }
1868                    if (hadFocus && !focusView.hasFocus()) {
1869                        focusView.requestFocus();
1870                    }
1871                }
1872            }
1873        } else {
1874            mInLayoutSearchFocus = hadFocus;
1875            if (mFocusPosition != NO_POSITION) {
1876                // appends items till focus position.
1877                while (appendOneColumnVisibleItems()
1878                        && findViewByPosition(mFocusPosition) == null) ;
1879            }
1880            // multiple rounds: scrollToView of first round may drag first/last child into
1881            // "visible window" and we update scrollMin/scrollMax then run second scrollToView
1882            int oldFirstVisible;
1883            int oldLastVisible;
1884            do {
1885                updateScrollMin();
1886                updateScrollMax();
1887                oldFirstVisible = mGrid.getFirstVisibleIndex();
1888                oldLastVisible = mGrid.getLastVisibleIndex();
1889                View focusView = findViewByPosition(mFocusPosition);
1890                // we need force to initialize the child view's position
1891                scrollToView(focusView, false);
1892                if (focusView != null && hadFocus && !focusView.hasFocus()) {
1893                    focusView.requestFocus();
1894                }
1895                appendVisibleItems();
1896                prependVisibleItems();
1897                removeInvisibleViewsAtFront();
1898                removeInvisibleViewsAtEnd();
1899            } while (mGrid.getFirstVisibleIndex() != oldFirstVisible ||
1900                    mGrid.getLastVisibleIndex() != oldLastVisible);
1901        }
1902
1903        if (scrollToFocus) {
1904            scrollDirectionPrimary(-delta);
1905            scrollDirectionSecondary(-deltaSecondary);
1906        }
1907        appendVisibleItems();
1908        prependVisibleItems();
1909        removeInvisibleViewsAtFront();
1910        removeInvisibleViewsAtEnd();
1911
1912        if (DEBUG) {
1913            StringWriter sw = new StringWriter();
1914            PrintWriter pw = new PrintWriter(sw);
1915            mGrid.debugPrint(pw);
1916            Log.d(getTag(), sw.toString());
1917        }
1918
1919        if (mRowSecondarySizeRefresh) {
1920            mRowSecondarySizeRefresh = false;
1921        } else {
1922            updateRowSecondarySizeRefresh();
1923        }
1924
1925        // For fastRelayout, only dispatch event when focus position changes.
1926        if (mInFastRelayout && (mFocusPosition != savedFocusPos || mSubFocusPosition !=
1927                savedSubFocusPos || findViewByPosition(mFocusPosition) != savedFocusView)) {
1928            dispatchChildSelected();
1929        } else if (!mInFastRelayout && mInLayoutSearchFocus) {
1930            // For full layout we dispatchChildSelected() in createItem() unless searched all
1931            // children and found none is focusable then dispatchChildSelected() here.
1932            dispatchChildSelected();
1933        }
1934
1935        mInLayout = false;
1936        leaveContext();
1937        if (DEBUG) Log.v(getTag(), "layoutChildren end");
1938    }
1939
1940    private void offsetChildrenSecondary(int increment) {
1941        final int childCount = getChildCount();
1942        if (mOrientation == HORIZONTAL) {
1943            for (int i = 0; i < childCount; i++) {
1944                getChildAt(i).offsetTopAndBottom(increment);
1945            }
1946        } else {
1947            for (int i = 0; i < childCount; i++) {
1948                getChildAt(i).offsetLeftAndRight(increment);
1949            }
1950        }
1951    }
1952
1953    private void offsetChildrenPrimary(int increment) {
1954        final int childCount = getChildCount();
1955        if (mOrientation == VERTICAL) {
1956            for (int i = 0; i < childCount; i++) {
1957                getChildAt(i).offsetTopAndBottom(increment);
1958            }
1959        } else {
1960            for (int i = 0; i < childCount; i++) {
1961                getChildAt(i).offsetLeftAndRight(increment);
1962            }
1963        }
1964    }
1965
1966    @Override
1967    public int scrollHorizontallyBy(int dx, Recycler recycler, RecyclerView.State state) {
1968        if (DEBUG) Log.v(getTag(), "scrollHorizontallyBy " + dx);
1969        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1970            return 0;
1971        }
1972        saveContext(recycler, state);
1973        mInScroll = true;
1974        int result;
1975        if (mOrientation == HORIZONTAL) {
1976            result = scrollDirectionPrimary(dx);
1977        } else {
1978            result = scrollDirectionSecondary(dx);
1979        }
1980        leaveContext();
1981        mInScroll = false;
1982        return result;
1983    }
1984
1985    @Override
1986    public int scrollVerticallyBy(int dy, Recycler recycler, RecyclerView.State state) {
1987        if (DEBUG) Log.v(getTag(), "scrollVerticallyBy " + dy);
1988        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1989            return 0;
1990        }
1991        mInScroll = true;
1992        saveContext(recycler, state);
1993        int result;
1994        if (mOrientation == VERTICAL) {
1995            result = scrollDirectionPrimary(dy);
1996        } else {
1997            result = scrollDirectionSecondary(dy);
1998        }
1999        leaveContext();
2000        mInScroll = false;
2001        return result;
2002    }
2003
2004    // scroll in main direction may add/prune views
2005    private int scrollDirectionPrimary(int da) {
2006        if (TRACE) TraceHelper.beginSection("scrollPrimary");
2007        boolean isMaxUnknown = false, isMinUnknown = false;
2008        int minScroll = 0, maxScroll = 0;
2009        if (da > 0) {
2010            isMaxUnknown = mWindowAlignment.mainAxis().isMaxUnknown();
2011            if (!isMaxUnknown) {
2012                maxScroll = mWindowAlignment.mainAxis().getMaxScroll();
2013                if (mScrollOffsetPrimary + da > maxScroll) {
2014                    da = maxScroll - mScrollOffsetPrimary;
2015                }
2016            }
2017        } else if (da < 0) {
2018            isMinUnknown = mWindowAlignment.mainAxis().isMinUnknown();
2019            if (!isMinUnknown) {
2020                minScroll = mWindowAlignment.mainAxis().getMinScroll();
2021                if (mScrollOffsetPrimary + da < minScroll) {
2022                    da = minScroll - mScrollOffsetPrimary;
2023                }
2024            }
2025        }
2026        if (da == 0) {
2027            if (TRACE) TraceHelper.endSection();
2028            return 0;
2029        }
2030        offsetChildrenPrimary(-da);
2031        mScrollOffsetPrimary += da;
2032        if (mInLayout) {
2033            if (TRACE) TraceHelper.endSection();
2034            return da;
2035        }
2036
2037        int childCount = getChildCount();
2038        boolean updated;
2039
2040        if (mReverseFlowPrimary ? da > 0 : da < 0) {
2041            prependVisibleItems();
2042        } else {
2043            appendVisibleItems();
2044        }
2045        updated = getChildCount() > childCount;
2046        childCount = getChildCount();
2047
2048        if (TRACE) TraceHelper.beginSection("remove");
2049        if (mReverseFlowPrimary ? da > 0 : da < 0) {
2050            removeInvisibleViewsAtEnd();
2051        } else {
2052            removeInvisibleViewsAtFront();
2053        }
2054        if (TRACE) TraceHelper.endSection();
2055        updated |= getChildCount() < childCount;
2056        if (updated) {
2057            updateRowSecondarySizeRefresh();
2058        }
2059
2060        mBaseGridView.invalidate();
2061        if (TRACE) TraceHelper.endSection();
2062        return da;
2063    }
2064
2065    // scroll in second direction will not add/prune views
2066    private int scrollDirectionSecondary(int dy) {
2067        if (dy == 0) {
2068            return 0;
2069        }
2070        offsetChildrenSecondary(-dy);
2071        mScrollOffsetSecondary += dy;
2072        mBaseGridView.invalidate();
2073        return dy;
2074    }
2075
2076    private void updateScrollMax() {
2077        int highVisiblePos = (!mReverseFlowPrimary) ? mGrid.getLastVisibleIndex()
2078                : mGrid.getFirstVisibleIndex();
2079        int highMaxPos = (!mReverseFlowPrimary) ? mState.getItemCount() - 1 : 0;
2080        if (highVisiblePos < 0) {
2081            return;
2082        }
2083        final boolean highAvailable = highVisiblePos == highMaxPos;
2084        final boolean maxUnknown = mWindowAlignment.mainAxis().isMaxUnknown();
2085        if (!highAvailable && maxUnknown) {
2086            return;
2087        }
2088        int maxEdge = mGrid.findRowMax(true, sTwoInts) + mScrollOffsetPrimary;
2089        int rowIndex = sTwoInts[0];
2090        int pos = sTwoInts[1];
2091        int savedMaxEdge = mWindowAlignment.mainAxis().getMaxEdge();
2092        mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
2093        int maxScroll = getPrimarySystemScrollPositionOfChildMax(findViewByPosition(pos));
2094        mWindowAlignment.mainAxis().setMaxEdge(savedMaxEdge);
2095
2096        if (highAvailable) {
2097            mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
2098            mWindowAlignment.mainAxis().setMaxScroll(maxScroll);
2099            if (DEBUG) Log.v(getTag(), "updating scroll maxEdge to " + maxEdge +
2100                    " scrollMax to " + maxScroll);
2101        } else {
2102            mWindowAlignment.mainAxis().invalidateScrollMax();
2103            if (DEBUG) Log.v(getTag(), "Invalidate scrollMax since it should be "
2104                    + "greater than " + maxScroll);
2105        }
2106    }
2107
2108    private void updateScrollMin() {
2109        int lowVisiblePos = (!mReverseFlowPrimary) ? mGrid.getFirstVisibleIndex()
2110                : mGrid.getLastVisibleIndex();
2111        int lowMinPos = (!mReverseFlowPrimary) ? 0 : mState.getItemCount() - 1;
2112        if (lowVisiblePos < 0) {
2113            return;
2114        }
2115        final boolean lowAvailable = lowVisiblePos == lowMinPos;
2116        final boolean minUnknown = mWindowAlignment.mainAxis().isMinUnknown();
2117        if (!lowAvailable && minUnknown) {
2118            return;
2119        }
2120        int minEdge = mGrid.findRowMin(false, sTwoInts) + mScrollOffsetPrimary;
2121        int rowIndex = sTwoInts[0];
2122        int pos = sTwoInts[1];
2123        int savedMinEdge = mWindowAlignment.mainAxis().getMinEdge();
2124        mWindowAlignment.mainAxis().setMinEdge(minEdge);
2125        int minScroll = getPrimarySystemScrollPosition(findViewByPosition(pos));
2126        mWindowAlignment.mainAxis().setMinEdge(savedMinEdge);
2127
2128        if (lowAvailable) {
2129            mWindowAlignment.mainAxis().setMinEdge(minEdge);
2130            mWindowAlignment.mainAxis().setMinScroll(minScroll);
2131            if (DEBUG) Log.v(getTag(), "updating scroll minEdge to " + minEdge +
2132                    " scrollMin to " + minScroll);
2133        } else {
2134            mWindowAlignment.mainAxis().invalidateScrollMin();
2135            if (DEBUG) Log.v(getTag(), "Invalidate scrollMin, since it should be "
2136                    + "less than " + minScroll);
2137        }
2138    }
2139
2140    private void updateScrollSecondAxis() {
2141        mWindowAlignment.secondAxis().setMinEdge(0);
2142        mWindowAlignment.secondAxis().setMaxEdge(getSizeSecondary());
2143    }
2144
2145    private void initScrollController() {
2146        mWindowAlignment.reset();
2147        mWindowAlignment.horizontal.setSize(getWidth());
2148        mWindowAlignment.vertical.setSize(getHeight());
2149        mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight());
2150        mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom());
2151        mSizePrimary = mWindowAlignment.mainAxis().getSize();
2152        mScrollOffsetPrimary = -mWindowAlignment.mainAxis().getPaddingLow();
2153        mScrollOffsetSecondary = -mWindowAlignment.secondAxis().getPaddingLow();
2154
2155        if (DEBUG) {
2156            Log.v(getTag(), "initScrollController mSizePrimary " + mSizePrimary
2157                    + " mWindowAlignment " + mWindowAlignment
2158                    + " mScrollOffsetPrimary " + mScrollOffsetPrimary);
2159        }
2160    }
2161
2162    private void updateScrollController() {
2163        // mScrollOffsetPrimary and mScrollOffsetSecondary includes the padding.
2164        // e.g. when topPadding is 16 for horizontal grid view,  the initial
2165        // mScrollOffsetSecondary is -16.  fastRelayout() put views based on offsets(not padding),
2166        // when padding changes to 20,  we also need update mScrollOffsetSecondary to -20 before
2167        // fastRelayout() is performed
2168        int paddingPrimaryDiff, paddingSecondaryDiff;
2169        if (mOrientation == HORIZONTAL) {
2170            paddingPrimaryDiff = getPaddingLeft() - mWindowAlignment.horizontal.getPaddingLow();
2171            paddingSecondaryDiff = getPaddingTop() - mWindowAlignment.vertical.getPaddingLow();
2172        } else {
2173            paddingPrimaryDiff = getPaddingTop() - mWindowAlignment.vertical.getPaddingLow();
2174            paddingSecondaryDiff = getPaddingLeft() - mWindowAlignment.horizontal.getPaddingLow();
2175        }
2176        mScrollOffsetPrimary -= paddingPrimaryDiff;
2177        mScrollOffsetSecondary -= paddingSecondaryDiff;
2178
2179        mWindowAlignment.horizontal.setSize(getWidth());
2180        mWindowAlignment.vertical.setSize(getHeight());
2181        mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight());
2182        mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom());
2183        mSizePrimary = mWindowAlignment.mainAxis().getSize();
2184
2185        if (DEBUG) {
2186            Log.v(getTag(), "updateScrollController mSizePrimary " + mSizePrimary
2187                    + " mWindowAlignment " + mWindowAlignment
2188                    + " mScrollOffsetPrimary " + mScrollOffsetPrimary);
2189        }
2190    }
2191
2192    @Override
2193    public void scrollToPosition(int position) {
2194        setSelection(position, 0, false, 0);
2195    }
2196
2197    public void setSelection(int position,
2198            int primaryScrollExtra) {
2199        setSelection(position, 0, false, primaryScrollExtra);
2200    }
2201
2202    public void setSelectionSmooth(int position) {
2203        setSelection(position, 0, true, 0);
2204    }
2205
2206    public void setSelectionWithSub(int position, int subposition,
2207            int primaryScrollExtra) {
2208        setSelection(position, subposition, false, primaryScrollExtra);
2209    }
2210
2211    public void setSelectionSmoothWithSub(int position, int subposition) {
2212        setSelection(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(int position, int subposition, boolean smooth,
2224            int primaryScrollExtra) {
2225        if (mFocusPosition != position && position != NO_POSITION
2226                || subposition != mSubFocusPosition || primaryScrollExtra != mPrimaryScrollExtra) {
2227            scrollToSelection(position, subposition, smooth, primaryScrollExtra);
2228        }
2229    }
2230
2231    private void scrollToSelection(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                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(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