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