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