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