GridLayoutManager.java revision 4200ae975bfd7e4dc2e5c2d838c070470fcb3e2a
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.animation.TimeAnimator;
17import android.content.Context;
18import android.graphics.PointF;
19import android.graphics.Rect;
20import android.support.v7.widget.LinearSmoothScroller;
21import android.support.v7.widget.RecyclerView;
22import android.support.v7.widget.RecyclerView.Recycler;
23import android.support.v7.widget.RecyclerView.State;
24
25import static android.support.v7.widget.RecyclerView.NO_ID;
26import static android.support.v7.widget.RecyclerView.NO_POSITION;
27import static android.support.v7.widget.RecyclerView.HORIZONTAL;
28import static android.support.v7.widget.RecyclerView.VERTICAL;
29
30import android.util.AttributeSet;
31import android.util.Log;
32import android.view.FocusFinder;
33import android.view.Gravity;
34import android.view.View;
35import android.view.ViewParent;
36import android.view.View.MeasureSpec;
37import android.view.ViewGroup.MarginLayoutParams;
38import android.view.ViewGroup;
39import android.view.animation.DecelerateInterpolator;
40import android.view.animation.Interpolator;
41
42import java.io.PrintWriter;
43import java.io.StringWriter;
44import java.util.ArrayList;
45import java.util.List;
46
47final class GridLayoutManager extends RecyclerView.LayoutManager {
48
49     /*
50      * LayoutParams for {@link HorizontalGridView} and {@link VerticalGridView}.
51      * The class currently does two internal jobs:
52      * - Saves optical bounds insets.
53      * - Caches focus align view center.
54      */
55    static class LayoutParams extends RecyclerView.LayoutParams {
56
57        // The view is saved only during animation.
58        private View mView;
59
60        // For placement
61        private int mLeftInset;
62        private int mTopInset;
63        private int mRighInset;
64        private int mBottomInset;
65
66        // For alignment
67        private int mAlignX;
68        private int mAlignY;
69
70        public LayoutParams(Context c, AttributeSet attrs) {
71            super(c, attrs);
72        }
73
74        public LayoutParams(int width, int height) {
75            super(width, height);
76        }
77
78        public LayoutParams(MarginLayoutParams source) {
79            super(source);
80        }
81
82        public LayoutParams(ViewGroup.LayoutParams source) {
83            super(source);
84        }
85
86        public LayoutParams(RecyclerView.LayoutParams source) {
87            super(source);
88        }
89
90        public LayoutParams(LayoutParams source) {
91            super(source);
92        }
93
94        int getAlignX() {
95            return mAlignX;
96        }
97
98        int getAlignY() {
99            return mAlignY;
100        }
101
102        int getOpticalLeft(View view) {
103            return view.getLeft() + mLeftInset;
104        }
105
106        int getOpticalTop(View view) {
107            return view.getTop() + mTopInset;
108        }
109
110        int getOpticalRight(View view) {
111            return view.getRight() - mRighInset;
112        }
113
114        int getOpticalBottom(View view) {
115            return view.getBottom() - mBottomInset;
116        }
117
118        int getOpticalWidth(View view) {
119            return view.getWidth() - mLeftInset - mRighInset;
120        }
121
122        int getOpticalHeight(View view) {
123            return view.getHeight() - mTopInset - mBottomInset;
124        }
125
126        int getOpticalLeftInset() {
127            return mLeftInset;
128        }
129
130        int getOpticalRightInset() {
131            return mRighInset;
132        }
133
134        int getOpticalTopInset() {
135            return mTopInset;
136        }
137
138        int getOpticalBottomInset() {
139            return mBottomInset;
140        }
141
142        void setAlignX(int alignX) {
143            mAlignX = alignX;
144        }
145
146        void setAlignY(int alignY) {
147            mAlignY = alignY;
148        }
149
150        void setOpticalInsets(int leftInset, int topInset, int rightInset, int bottomInset) {
151            mLeftInset = leftInset;
152            mTopInset = topInset;
153            mRighInset = rightInset;
154            mBottomInset = bottomInset;
155        }
156
157        private void invalidateItemDecoration() {
158            ViewParent parent = mView.getParent();
159            if (parent instanceof RecyclerView) {
160                // TODO: we only need invalidate parent if it has ItemDecoration
161                ((RecyclerView) parent).invalidate();
162            }
163        }
164    }
165
166    private static final String TAG = "GridLayoutManager";
167    private static final boolean DEBUG = false;
168
169    private static final Interpolator sDefaultAnimationChildLayoutInterpolator
170            = new DecelerateInterpolator();
171
172    private static final long DEFAULT_CHILD_ANIMATION_DURATION_MS = 250;
173
174    private String getTag() {
175        return TAG + ":" + mBaseGridView.getId();
176    }
177
178    private final BaseGridView mBaseGridView;
179
180    /**
181     * The orientation of a "row".
182     */
183    private int mOrientation = HORIZONTAL;
184
185    private RecyclerView.State mState;
186    private RecyclerView.Recycler mRecycler;
187
188    private boolean mInLayout = false;
189
190    private OnChildSelectedListener mChildSelectedListener = null;
191
192    /**
193     * The focused position, it's not the currently visually aligned position
194     * but it is the final position that we intend to focus on. If there are
195     * multiple setSelection() called, mFocusPosition saves last value.
196     */
197    private int mFocusPosition = NO_POSITION;
198
199    /**
200     * Force a full layout under certain situations.
201     */
202    private boolean mForceFullLayout;
203
204    /**
205     * True if layout is enabled.
206     */
207    private boolean mLayoutEnabled = true;
208
209    /**
210     * The scroll offsets of the viewport relative to the entire view.
211     */
212    private int mScrollOffsetPrimary;
213    private int mScrollOffsetSecondary;
214
215    /**
216     * User-specified row height/column width.  Can be WRAP_CONTENT.
217     */
218    private int mRowSizeSecondaryRequested;
219
220    /**
221     * The fixed size of each grid item in the secondary direction. This corresponds to
222     * the row height, equal for all rows. Grid items may have variable length
223     * in the primary direction.
224     */
225    private int mFixedRowSizeSecondary;
226
227    /**
228     * Tracks the secondary size of each row.
229     */
230    private int[] mRowSizeSecondary;
231
232    /**
233     * Flag controlling whether the current/next layout should
234     * be updating the secondary size of rows.
235     */
236    private boolean mRowSecondarySizeRefresh;
237
238    /**
239     * The maximum measured size of the view.
240     */
241    private int mMaxSizeSecondary;
242
243    /**
244     * Margin between items.
245     */
246    private int mHorizontalMargin;
247    /**
248     * Margin between items vertically.
249     */
250    private int mVerticalMargin;
251    /**
252     * Margin in main direction.
253     */
254    private int mMarginPrimary;
255    /**
256     * Margin in second direction.
257     */
258    private int mMarginSecondary;
259    /**
260     * How to position child in secondary direction.
261     */
262    private int mGravity = Gravity.LEFT | Gravity.TOP;
263    /**
264     * The number of rows in the grid.
265     */
266    private int mNumRows;
267    /**
268     * Number of rows requested, can be 0 to be determined by parent size and
269     * rowHeight.
270     */
271    private int mNumRowsRequested = 1;
272
273    /**
274     * Tracking start/end position of each row for visible items.
275     */
276    private StaggeredGrid.Row[] mRows;
277
278    /**
279     * Saves grid information of each view.
280     */
281    private StaggeredGrid mGrid;
282    /**
283     * Position of first item (included) that has attached views.
284     */
285    private int mFirstVisiblePos;
286    /**
287     * Position of last item (included) that has attached views.
288     */
289    private int mLastVisiblePos;
290
291    /**
292     * Focus Scroll strategy.
293     */
294    private int mFocusScrollStrategy = BaseGridView.FOCUS_SCROLL_ALIGNED;
295    /**
296     * Defines how item view is aligned in the window.
297     */
298    private final WindowAlignment mWindowAlignment = new WindowAlignment();
299
300    /**
301     * Defines how item view is aligned.
302     */
303    private final ItemAlignment mItemAlignment = new ItemAlignment();
304
305    /**
306     * Dimensions of the view, width or height depending on orientation.
307     */
308    private int mSizePrimary;
309
310    /**
311     *  Allow DPAD key to navigate out at the front of the View (where position = 0),
312     *  default is false.
313     */
314    private boolean mFocusOutFront;
315
316    /**
317     * Allow DPAD key to navigate out at the end of the view, default is false.
318     */
319    private boolean mFocusOutEnd;
320
321    /**
322     * True if focus search is disabled.
323     */
324    private boolean mFocusSearchDisabled;
325
326    /**
327     * Animate layout changes from a child resizing or adding/removing a child.
328     */
329    private boolean mAnimateChildLayout = true;
330
331    /**
332     * True if prune child,  might be disabled during transition.
333     */
334    private boolean mPruneChild = true;
335
336    private int[] mTempDeltas = new int[2];
337
338    private boolean mUseDeltaInPreLayout;
339
340    private int mDeltaInPreLayout, mDeltaSecondaryInPreLayout;
341
342    public GridLayoutManager(BaseGridView baseGridView) {
343        mBaseGridView = baseGridView;
344    }
345
346    public void setOrientation(int orientation) {
347        if (orientation != HORIZONTAL && orientation != VERTICAL) {
348            if (DEBUG) Log.v(getTag(), "invalid orientation: " + orientation);
349            return;
350        }
351
352        mOrientation = orientation;
353        mWindowAlignment.setOrientation(orientation);
354        mItemAlignment.setOrientation(orientation);
355        mForceFullLayout = true;
356    }
357
358    public int getFocusScrollStrategy() {
359        return mFocusScrollStrategy;
360    }
361
362    public void setFocusScrollStrategy(int focusScrollStrategy) {
363        mFocusScrollStrategy = focusScrollStrategy;
364    }
365
366    public void setWindowAlignment(int windowAlignment) {
367        mWindowAlignment.mainAxis().setWindowAlignment(windowAlignment);
368    }
369
370    public int getWindowAlignment() {
371        return mWindowAlignment.mainAxis().getWindowAlignment();
372    }
373
374    public void setWindowAlignmentOffset(int alignmentOffset) {
375        mWindowAlignment.mainAxis().setWindowAlignmentOffset(alignmentOffset);
376    }
377
378    public int getWindowAlignmentOffset() {
379        return mWindowAlignment.mainAxis().getWindowAlignmentOffset();
380    }
381
382    public void setWindowAlignmentOffsetPercent(float offsetPercent) {
383        mWindowAlignment.mainAxis().setWindowAlignmentOffsetPercent(offsetPercent);
384    }
385
386    public float getWindowAlignmentOffsetPercent() {
387        return mWindowAlignment.mainAxis().getWindowAlignmentOffsetPercent();
388    }
389
390    public void setItemAlignmentOffset(int alignmentOffset) {
391        mItemAlignment.mainAxis().setItemAlignmentOffset(alignmentOffset);
392        updateChildAlignments();
393    }
394
395    public int getItemAlignmentOffset() {
396        return mItemAlignment.mainAxis().getItemAlignmentOffset();
397    }
398
399    public void setItemAlignmentOffsetWithPadding(boolean withPadding) {
400        mItemAlignment.mainAxis().setItemAlignmentOffsetWithPadding(withPadding);
401        updateChildAlignments();
402    }
403
404    public boolean isItemAlignmentOffsetWithPadding() {
405        return mItemAlignment.mainAxis().isItemAlignmentOffsetWithPadding();
406    }
407
408    public void setItemAlignmentOffsetPercent(float offsetPercent) {
409        mItemAlignment.mainAxis().setItemAlignmentOffsetPercent(offsetPercent);
410        updateChildAlignments();
411    }
412
413    public float getItemAlignmentOffsetPercent() {
414        return mItemAlignment.mainAxis().getItemAlignmentOffsetPercent();
415    }
416
417    public void setItemAlignmentViewId(int viewId) {
418        mItemAlignment.mainAxis().setItemAlignmentViewId(viewId);
419        updateChildAlignments();
420    }
421
422    public int getItemAlignmentViewId() {
423        return mItemAlignment.mainAxis().getItemAlignmentViewId();
424    }
425
426    public void setFocusOutAllowed(boolean throughFront, boolean throughEnd) {
427        mFocusOutFront = throughFront;
428        mFocusOutEnd = throughEnd;
429    }
430
431    public void setNumRows(int numRows) {
432        if (numRows < 0) throw new IllegalArgumentException();
433        mNumRowsRequested = numRows;
434        mForceFullLayout = true;
435    }
436
437    /**
438     * Set the row height. May be WRAP_CONTENT, or a size in pixels.
439     */
440    public void setRowHeight(int height) {
441        if (height >= 0 || height == ViewGroup.LayoutParams.WRAP_CONTENT) {
442            mRowSizeSecondaryRequested = height;
443        } else {
444            throw new IllegalArgumentException("Invalid row height: " + height);
445        }
446    }
447
448    public void setItemMargin(int margin) {
449        mVerticalMargin = mHorizontalMargin = margin;
450        mMarginPrimary = mMarginSecondary = margin;
451    }
452
453    public void setVerticalMargin(int margin) {
454        if (mOrientation == HORIZONTAL) {
455            mMarginSecondary = mVerticalMargin = margin;
456        } else {
457            mMarginPrimary = mVerticalMargin = margin;
458        }
459    }
460
461    public void setHorizontalMargin(int margin) {
462        if (mOrientation == HORIZONTAL) {
463            mMarginPrimary = mHorizontalMargin = margin;
464        } else {
465            mMarginSecondary = mHorizontalMargin = margin;
466        }
467    }
468
469    public int getVerticalMargin() {
470        return mVerticalMargin;
471    }
472
473    public int getHorizontalMargin() {
474        return mHorizontalMargin;
475    }
476
477    public void setGravity(int gravity) {
478        mGravity = gravity;
479    }
480
481    protected boolean hasDoneFirstLayout() {
482        return mGrid != null;
483    }
484
485    public void setOnChildSelectedListener(OnChildSelectedListener listener) {
486        mChildSelectedListener = listener;
487    }
488
489    private int getPositionByView(View view) {
490        if (view == null) {
491            return NO_POSITION;
492        }
493        RecyclerView.ViewHolder vh = mBaseGridView.getChildViewHolder(view);
494        if (vh == null) {
495            return NO_POSITION;
496        }
497        return vh.getPosition();
498    }
499
500    private int getPositionByIndex(int index) {
501        return getPositionByView(getChildAt(index));
502    }
503
504    private void dispatchChildSelected() {
505        if (mChildSelectedListener == null) {
506            return;
507        }
508        if (mFocusPosition != NO_POSITION) {
509            View view = findViewByPosition(mFocusPosition);
510            if (view != null) {
511                RecyclerView.ViewHolder vh = mBaseGridView.getChildViewHolder(view);
512                mChildSelectedListener.onChildSelected(mBaseGridView, view, mFocusPosition,
513                        vh == null? NO_ID: vh.getItemId());
514                return;
515            }
516        }
517        mChildSelectedListener.onChildSelected(mBaseGridView, null, NO_POSITION, NO_ID);
518    }
519
520    @Override
521    public boolean canScrollHorizontally() {
522        // We can scroll horizontally if we have horizontal orientation, or if
523        // we are vertical and have more than one column.
524        return mOrientation == HORIZONTAL || mNumRows > 1;
525    }
526
527    @Override
528    public boolean canScrollVertically() {
529        // We can scroll vertically if we have vertical orientation, or if we
530        // are horizontal and have more than one row.
531        return mOrientation == VERTICAL || mNumRows > 1;
532    }
533
534    @Override
535    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
536        return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
537                ViewGroup.LayoutParams.WRAP_CONTENT);
538    }
539
540    @Override
541    public RecyclerView.LayoutParams generateLayoutParams(Context context, AttributeSet attrs) {
542        return new LayoutParams(context, attrs);
543    }
544
545    @Override
546    public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
547        if (lp instanceof LayoutParams) {
548            return new LayoutParams((LayoutParams) lp);
549        } else if (lp instanceof RecyclerView.LayoutParams) {
550            return new LayoutParams((RecyclerView.LayoutParams) lp);
551        } else if (lp instanceof MarginLayoutParams) {
552            return new LayoutParams((MarginLayoutParams) lp);
553        } else {
554            return new LayoutParams(lp);
555        }
556    }
557
558    protected View getViewForPosition(int position) {
559        return mRecycler.getViewForPosition(position);
560    }
561
562    final int getOpticalLeft(View v) {
563        return ((LayoutParams) v.getLayoutParams()).getOpticalLeft(v);
564    }
565
566    final int getOpticalRight(View v) {
567        return ((LayoutParams) v.getLayoutParams()).getOpticalRight(v);
568    }
569
570    final int getOpticalTop(View v) {
571        return ((LayoutParams) v.getLayoutParams()).getOpticalTop(v);
572    }
573
574    final int getOpticalBottom(View v) {
575        return ((LayoutParams) v.getLayoutParams()).getOpticalBottom(v);
576    }
577
578    private int getViewMin(View v) {
579        return (mOrientation == HORIZONTAL) ? getOpticalLeft(v) : getOpticalTop(v);
580    }
581
582    private int getViewMax(View v) {
583        return (mOrientation == HORIZONTAL) ? getOpticalRight(v) : getOpticalBottom(v);
584    }
585
586    private int getViewCenter(View view) {
587        return (mOrientation == HORIZONTAL) ? getViewCenterX(view) : getViewCenterY(view);
588    }
589
590    private int getViewCenterSecondary(View view) {
591        return (mOrientation == HORIZONTAL) ? getViewCenterY(view) : getViewCenterX(view);
592    }
593
594    private int getViewCenterX(View v) {
595        LayoutParams p = (LayoutParams) v.getLayoutParams();
596        return p.getOpticalLeft(v) + p.getAlignX();
597    }
598
599    private int getViewCenterY(View v) {
600        LayoutParams p = (LayoutParams) v.getLayoutParams();
601        return p.getOpticalTop(v) + p.getAlignY();
602    }
603
604    /**
605     * Save Recycler and State for convenience.  Must be paired with leaveContext().
606     */
607    private void saveContext(Recycler recycler, State state) {
608        if (mRecycler != null || mState != null) {
609            Log.e(TAG, "Recycler information was not released, bug!");
610        }
611        mRecycler = recycler;
612        mState = state;
613    }
614
615    /**
616     * Discard saved Recycler and State.
617     */
618    private void leaveContext() {
619        mRecycler = null;
620        mState = null;
621    }
622
623    /**
624     * Re-initialize data structures for a data change or handling invisible
625     * selection. The method tries its best to preserve position information so
626     * that staggered grid looks same before and after re-initialize.
627     * @param focusPosition The initial focusPosition that we would like to
628     *        focus on.
629     * @return Actual position that can be focused on.
630     */
631    private int init(int focusPosition) {
632
633        final int newItemCount = mState.getItemCount();
634
635        if (focusPosition == NO_POSITION && newItemCount > 0) {
636            // if focus position is never set before,  initialize it to 0
637            focusPosition = 0;
638        }
639        // If adapter has changed then caches are invalid; otherwise,
640        // we try to maintain each row's position if number of rows keeps the same
641        // and existing mGrid contains the focusPosition.
642        if (mRows != null && mNumRows == mRows.length &&
643                mGrid != null && mGrid.getSize() > 0 && focusPosition >= 0 &&
644                focusPosition >= mGrid.getFirstIndex() &&
645                focusPosition <= mGrid.getLastIndex()) {
646            // strip mGrid to a subset (like a column) that contains focusPosition
647            mGrid.stripDownTo(focusPosition);
648            // make sure that remaining items do not exceed new adapter size
649            int firstIndex = mGrid.getFirstIndex();
650            int lastIndex = mGrid.getLastIndex();
651            if (DEBUG) {
652                Log .v(getTag(), "mGrid firstIndex " + firstIndex + " lastIndex " + lastIndex);
653            }
654            for (int i = lastIndex; i >=firstIndex; i--) {
655                if (i >= newItemCount) {
656                    mGrid.removeLast();
657                }
658            }
659            if (mGrid.getSize() == 0) {
660                focusPosition = newItemCount - 1;
661                // initialize row start locations
662                for (int i = 0; i < mNumRows; i++) {
663                    mRows[i].low = 0;
664                    mRows[i].high = 0;
665                }
666                if (DEBUG) Log.v(getTag(), "mGrid zero size");
667            } else {
668                // initialize row start locations
669                for (int i = 0; i < mNumRows; i++) {
670                    mRows[i].low = Integer.MAX_VALUE;
671                    mRows[i].high = Integer.MIN_VALUE;
672                }
673                firstIndex = mGrid.getFirstIndex();
674                lastIndex = mGrid.getLastIndex();
675                if (focusPosition > lastIndex) {
676                    focusPosition = mGrid.getLastIndex();
677                }
678                if (DEBUG) {
679                    Log.v(getTag(), "mGrid firstIndex " + firstIndex + " lastIndex "
680                        + lastIndex + " focusPosition " + focusPosition);
681                }
682                // fill rows with minimal view positions of the subset
683                for (int i = firstIndex; i <= lastIndex; i++) {
684                    View v = findViewByPosition(i);
685                    if (v == null) {
686                        continue;
687                    }
688                    int row = mGrid.getLocation(i).row;
689                    int low = getViewMin(v) + mScrollOffsetPrimary;
690                    if (low < mRows[row].low) {
691                        mRows[row].low = mRows[row].high = low;
692                    }
693                }
694                int firstItemRowPosition = mRows[mGrid.getLocation(firstIndex).row].low;
695                if (firstItemRowPosition == Integer.MAX_VALUE) {
696                    firstItemRowPosition = 0;
697                }
698                if (mState.didStructureChange()) {
699                    // if there is structure change, the removed item might be in the
700                    // subset,  so it is meaningless to maintain the low locations.
701                    for (int i = 0; i < mNumRows; i++) {
702                        mRows[i].low = firstItemRowPosition;
703                        mRows[i].high = firstItemRowPosition;
704                    }
705                } else {
706                    // fill other rows that does not include the subset using first item
707                    for (int i = 0; i < mNumRows; i++) {
708                        if (mRows[i].low == Integer.MAX_VALUE) {
709                            mRows[i].low = mRows[i].high = firstItemRowPosition;
710                        }
711                    }
712                }
713            }
714
715            // Same adapter, we can reuse any attached views
716            detachAndScrapAttachedViews(mRecycler);
717
718        } else {
719            // otherwise recreate data structure
720            mRows = new StaggeredGrid.Row[mNumRows];
721            mRowSizeSecondary = new int[mNumRows];
722
723            for (int i = 0; i < mNumRows; i++) {
724                mRows[i] = new StaggeredGrid.Row();
725            }
726            mGrid = new StaggeredGridDefault();
727            if (newItemCount == 0) {
728                focusPosition = NO_POSITION;
729            } else if (focusPosition >= newItemCount) {
730                focusPosition = newItemCount - 1;
731            }
732
733            // Adapter may have changed so remove all attached views permanently
734            removeAllViews();
735
736            mScrollOffsetPrimary = 0;
737            mScrollOffsetSecondary = 0;
738            mWindowAlignment.reset();
739        }
740
741        mGrid.setProvider(mGridProvider);
742        // mGrid share the same Row array information
743        mGrid.setRows(mRows);
744        mFirstVisiblePos = mLastVisiblePos = NO_POSITION;
745
746        initScrollController();
747        updateScrollSecondAxis();
748
749        return focusPosition;
750    }
751
752    private int getRowSizeSecondary(int rowIndex) {
753        if (mFixedRowSizeSecondary != 0) {
754            return mFixedRowSizeSecondary;
755        }
756        if (mRowSizeSecondary == null) {
757            return 0;
758        }
759        return mRowSizeSecondary[rowIndex];
760    }
761
762    private int getRowStartSecondary(int rowIndex) {
763        int start = 0;
764        for (int i = 0; i < rowIndex; i++) {
765            start += getRowSizeSecondary(i) + mMarginSecondary;
766        }
767        return start;
768    }
769
770    private int getSizeSecondary() {
771        return getRowStartSecondary(mNumRows - 1) + getRowSizeSecondary(mNumRows - 1);
772    }
773
774    private boolean processRowSizeSecondary(boolean measure) {
775        if (mFixedRowSizeSecondary != 0) {
776            return false;
777        }
778
779        List<Integer>[] rows = mGrid.getItemPositionsInRows(mFirstVisiblePos, mLastVisiblePos);
780        boolean changed = false;
781
782        for (int rowIndex = 0; rowIndex < mNumRows; rowIndex++) {
783            int rowSize = 0;
784
785            final int rowItemCount = rows[rowIndex].size();
786            if (DEBUG) Log.v(getTag(), "processRowSizeSecondary row " + rowIndex +
787                    " rowItemCount " + rowItemCount);
788
789            for (int i = 0; i < rowItemCount; i++) {
790                final int position = rows[rowIndex].get(i);
791                final View view = findViewByPosition(position);
792                if (measure && view.isLayoutRequested()) {
793                    measureChild(view, rowIndex);
794                }
795                // If this view isn't visible, we ignore it.
796                if (getOpticalRight(view) < 0 || getOpticalLeft(view) > getWidth() ||
797                        getOpticalBottom(view) < 0 || getOpticalTop(view) > getHeight()) {
798                    continue;
799                }
800                final int secondarySize = mOrientation == HORIZONTAL ?
801                        view.getMeasuredHeight() : view.getMeasuredWidth();
802                if (secondarySize > rowSize) {
803                    rowSize = secondarySize;
804                }
805            }
806            if (DEBUG) Log.v(getTag(), "row " + rowIndex + " rowItemCount " + rowItemCount +
807                    " rowSize " + rowSize);
808
809            if (mRowSizeSecondary[rowIndex] != rowSize) {
810                if (DEBUG) Log.v(getTag(), "row size secondary changed: " + mRowSizeSecondary[rowIndex] +
811                        ", " + rowSize);
812
813                mRowSizeSecondary[rowIndex] = rowSize;
814                changed = true;
815            }
816        }
817
818        return changed;
819    }
820
821    /**
822     * Checks if we need to update row secondary sizes.
823     */
824    private void updateRowSecondarySizeRefresh() {
825        mRowSecondarySizeRefresh = processRowSizeSecondary(false);
826        if (mRowSecondarySizeRefresh) {
827            if (DEBUG) Log.v(getTag(), "mRowSecondarySizeRefresh now set");
828            forceRequestLayout();
829        }
830    }
831
832    private void forceRequestLayout() {
833        if (DEBUG) Log.v(getTag(), "forceRequestLayout");
834        // RecyclerView prevents us from requesting layout in many cases
835        // (during layout, during scroll, etc.)
836        // For secondary row size wrap_content support we currently need a
837        // second layout pass to update the measured size after having measured
838        // and added child views in layoutChildren.
839        // Force the second layout by posting a delayed runnable.
840        // TODO: investigate allowing a second layout pass,
841        // or move child add/measure logic to the measure phase.
842        mBaseGridView.getHandler().post(new Runnable() {
843           @Override
844           public void run() {
845               if (DEBUG) Log.v(getTag(), "request Layout from runnable");
846               requestLayout();
847           }
848        });
849    }
850
851    @Override
852    public void onMeasure(int widthSpec, int heightSpec) {
853        int sizePrimary, sizeSecondary, modeSecondary, paddingSecondary;
854        int measuredSizeSecondary;
855        if (mOrientation == HORIZONTAL) {
856            sizePrimary = MeasureSpec.getSize(widthSpec);
857            sizeSecondary = MeasureSpec.getSize(heightSpec);
858            modeSecondary = MeasureSpec.getMode(heightSpec);
859            paddingSecondary = getPaddingTop() + getPaddingBottom();
860        } else {
861            sizeSecondary = MeasureSpec.getSize(widthSpec);
862            sizePrimary = MeasureSpec.getSize(heightSpec);
863            modeSecondary = MeasureSpec.getMode(widthSpec);
864            paddingSecondary = getPaddingLeft() + getPaddingRight();
865        }
866        if (DEBUG) Log.v(getTag(), "onMeasure widthSpec " + Integer.toHexString(widthSpec) +
867                " heightSpec " + Integer.toHexString(heightSpec) +
868                " modeSecondary " + Integer.toHexString(modeSecondary) +
869                " sizeSecondary " + sizeSecondary + " " + this);
870
871        mMaxSizeSecondary = sizeSecondary;
872
873        if (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) {
874            mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested;
875            mFixedRowSizeSecondary = 0;
876
877            // Measure all current children and update cached row heights
878            if (mGrid != null) {
879                processRowSizeSecondary(true);
880            }
881
882            switch (modeSecondary) {
883            case MeasureSpec.UNSPECIFIED:
884                measuredSizeSecondary = getSizeSecondary() + paddingSecondary;
885                break;
886            case MeasureSpec.AT_MOST:
887                measuredSizeSecondary = Math.min(getSizeSecondary() + paddingSecondary,
888                        mMaxSizeSecondary);
889                break;
890            case MeasureSpec.EXACTLY:
891                measuredSizeSecondary = mMaxSizeSecondary;
892                break;
893            default:
894                throw new IllegalStateException("wrong spec");
895            }
896
897        } else {
898            switch (modeSecondary) {
899            case MeasureSpec.UNSPECIFIED:
900                if (mRowSizeSecondaryRequested == 0) {
901                    if (mOrientation == HORIZONTAL) {
902                        throw new IllegalStateException("Must specify rowHeight or view height");
903                    } else {
904                        throw new IllegalStateException("Must specify columnWidth or view width");
905                    }
906                }
907                mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
908                mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested;
909                measuredSizeSecondary = mFixedRowSizeSecondary * mNumRows + mMarginSecondary
910                    * (mNumRows - 1) + paddingSecondary;
911                break;
912            case MeasureSpec.AT_MOST:
913            case MeasureSpec.EXACTLY:
914                if (mNumRowsRequested == 0 && mRowSizeSecondaryRequested == 0) {
915                    mNumRows = 1;
916                    mFixedRowSizeSecondary = sizeSecondary - paddingSecondary;
917                } else if (mNumRowsRequested == 0) {
918                    mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
919                    mNumRows = (sizeSecondary + mMarginSecondary)
920                        / (mRowSizeSecondaryRequested + mMarginSecondary);
921                } else if (mRowSizeSecondaryRequested == 0) {
922                    mNumRows = mNumRowsRequested;
923                    mFixedRowSizeSecondary = (sizeSecondary - paddingSecondary - mMarginSecondary
924                            * (mNumRows - 1)) / mNumRows;
925                } else {
926                    mNumRows = mNumRowsRequested;
927                    mFixedRowSizeSecondary = mRowSizeSecondaryRequested;
928                }
929                measuredSizeSecondary = sizeSecondary;
930                if (modeSecondary == MeasureSpec.AT_MOST) {
931                    int childrenSize = mFixedRowSizeSecondary * mNumRows + mMarginSecondary
932                        * (mNumRows - 1) + paddingSecondary;
933                    if (childrenSize < measuredSizeSecondary) {
934                        measuredSizeSecondary = childrenSize;
935                    }
936                }
937                break;
938            default:
939                throw new IllegalStateException("wrong spec");
940            }
941        }
942        if (mOrientation == HORIZONTAL) {
943            setMeasuredDimension(sizePrimary, measuredSizeSecondary);
944        } else {
945            setMeasuredDimension(measuredSizeSecondary, sizePrimary);
946        }
947        if (DEBUG) {
948            Log.v(getTag(), "onMeasure sizePrimary " + sizePrimary +
949                    " measuredSizeSecondary " + measuredSizeSecondary +
950                    " mFixedRowSizeSecondary " + mFixedRowSizeSecondary +
951                    " mNumRows " + mNumRows);
952        }
953    }
954
955    private void measureChild(View child, int rowIndex) {
956        final ViewGroup.LayoutParams lp = child.getLayoutParams();
957        final int secondarySpec = (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) ?
958                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) :
959                MeasureSpec.makeMeasureSpec(mFixedRowSizeSecondary, MeasureSpec.EXACTLY);
960        int widthSpec, heightSpec;
961
962        if (mOrientation == HORIZONTAL) {
963            widthSpec = ViewGroup.getChildMeasureSpec(
964                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
965                    0, lp.width);
966            heightSpec = ViewGroup.getChildMeasureSpec(secondarySpec, 0, lp.height);
967        } else {
968            heightSpec = ViewGroup.getChildMeasureSpec(
969                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
970                    0, lp.height);
971            widthSpec = ViewGroup.getChildMeasureSpec(secondarySpec, 0, lp.width);
972        }
973
974        child.measure(widthSpec, heightSpec);
975
976        if (DEBUG) Log.v(getTag(), "measureChild secondarySpec " + Integer.toHexString(secondarySpec) +
977                " widthSpec " + Integer.toHexString(widthSpec) +
978                " heightSpec " + Integer.toHexString(heightSpec) +
979                " measuredWidth " + child.getMeasuredWidth() +
980                " measuredHeight " + child.getMeasuredHeight());
981        if (DEBUG) Log.v(getTag(), "child lp width " + lp.width + " height " + lp.height);
982    }
983
984    private StaggeredGrid.Provider mGridProvider = new StaggeredGrid.Provider() {
985
986        @Override
987        public int getCount() {
988            return mState.getItemCount();
989        }
990
991        @Override
992        public void createItem(int index, int rowIndex, boolean append) {
993            View v = getViewForPosition(index);
994            if (mFirstVisiblePos >= 0) {
995                // when StaggeredGrid append or prepend item, we must guarantee
996                // that sibling item has created views already.
997                if (append && index != mLastVisiblePos + 1) {
998                    throw new RuntimeException();
999                } else if (!append && index != mFirstVisiblePos - 1) {
1000                    throw new RuntimeException();
1001                }
1002            }
1003
1004            // See recyclerView docs:  we don't need re-add scraped view if it was removed.
1005            if (!((RecyclerView.LayoutParams) v.getLayoutParams()).isItemRemoved()) {
1006                if (append) {
1007                    addView(v);
1008                } else {
1009                    addView(v, 0);
1010                }
1011                measureChild(v, rowIndex);
1012            }
1013
1014            int length = mOrientation == HORIZONTAL ? v.getMeasuredWidth() : v.getMeasuredHeight();
1015            int start, end;
1016            if (append) {
1017                start = mRows[rowIndex].high;
1018                if (start != mRows[rowIndex].low) {
1019                    // if there are existing item in the row,  add margin between
1020                    start += mMarginPrimary;
1021                } else {
1022                    final int lastRow = mRows.length - 1;
1023                    if (lastRow != rowIndex && mRows[lastRow].high != mRows[lastRow].low) {
1024                        // if there are existing item in the last row, insert
1025                        // the new item after the last item of last row.
1026                        start = mRows[lastRow].high + mMarginPrimary;
1027                    }
1028                }
1029                end = start + length;
1030                mRows[rowIndex].high = end;
1031            } else {
1032                end = mRows[rowIndex].low;
1033                if (end != mRows[rowIndex].high) {
1034                    end -= mMarginPrimary;
1035                } else if (0 != rowIndex && mRows[0].high != mRows[0].low) {
1036                    // if there are existing item in the first row, insert
1037                    // the new item before the first item of first row.
1038                    end = mRows[0].low - mMarginPrimary;
1039                }
1040                start = end - length;
1041                mRows[rowIndex].low = start;
1042            }
1043            if (mFirstVisiblePos < 0) {
1044                mFirstVisiblePos = mLastVisiblePos = index;
1045            } else {
1046                if (append) {
1047                    mLastVisiblePos++;
1048                } else {
1049                    mFirstVisiblePos--;
1050                }
1051            }
1052            if (DEBUG) Log.v(getTag(), "start " + start + " end " + end);
1053            int startSecondary = getRowStartSecondary(rowIndex) - mScrollOffsetSecondary;
1054            layoutChild(rowIndex, v, start - mScrollOffsetPrimary, end - mScrollOffsetPrimary,
1055                    startSecondary);
1056            if (DEBUG) {
1057                Log.d(getTag(), "addView " + index + " " + v);
1058            }
1059            updateScrollMin();
1060            updateScrollMax();
1061        }
1062    };
1063
1064    private void layoutChild(int rowIndex, View v, int start, int end, int startSecondary) {
1065        int sizeSecondary = mOrientation == HORIZONTAL ? v.getMeasuredHeight()
1066                : v.getMeasuredWidth();
1067        if (mFixedRowSizeSecondary > 0) {
1068            sizeSecondary = Math.min(sizeSecondary, mFixedRowSizeSecondary);
1069        }
1070        final int verticalGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
1071        final int horizontalGravity = mGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
1072        if (mOrientation == HORIZONTAL && verticalGravity == Gravity.TOP
1073                || mOrientation == VERTICAL && horizontalGravity == Gravity.LEFT) {
1074            // do nothing
1075        } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.BOTTOM
1076                || mOrientation == VERTICAL && horizontalGravity == Gravity.RIGHT) {
1077            startSecondary += getRowSizeSecondary(rowIndex) - sizeSecondary;
1078        } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.CENTER_VERTICAL
1079                || mOrientation == VERTICAL && horizontalGravity == Gravity.CENTER_HORIZONTAL) {
1080            startSecondary += (getRowSizeSecondary(rowIndex) - sizeSecondary) / 2;
1081        }
1082        int left, top, right, bottom;
1083        if (mOrientation == HORIZONTAL) {
1084            left = start;
1085            top = startSecondary;
1086            right = end;
1087            bottom = startSecondary + sizeSecondary;
1088        } else {
1089            top = start;
1090            left = startSecondary;
1091            bottom = end;
1092            right = startSecondary + sizeSecondary;
1093        }
1094        v.layout(left, top, right, bottom);
1095        updateChildOpticalInsets(v, left, top, right, bottom);
1096        updateChildAlignments(v);
1097    }
1098
1099    private void updateChildOpticalInsets(View v, int left, int top, int right, int bottom) {
1100        LayoutParams p = (LayoutParams) v.getLayoutParams();
1101        p.setOpticalInsets(left - v.getLeft(), top - v.getTop(),
1102                v.getRight() - right, v.getBottom() - bottom);
1103    }
1104
1105    private void updateChildAlignments(View v) {
1106        LayoutParams p = (LayoutParams) v.getLayoutParams();
1107        p.setAlignX(mItemAlignment.horizontal.getAlignmentPosition(v));
1108        p.setAlignY(mItemAlignment.vertical.getAlignmentPosition(v));
1109    }
1110
1111    private void updateChildAlignments() {
1112        for (int i = 0, c = getChildCount(); i < c; i++) {
1113            updateChildAlignments(getChildAt(i));
1114        }
1115    }
1116
1117    private boolean needsAppendVisibleItem() {
1118        if (mLastVisiblePos < mFocusPosition) {
1119            return true;
1120        }
1121        int right = mScrollOffsetPrimary + mSizePrimary;
1122        for (int i = 0; i < mNumRows; i++) {
1123            if (mRows[i].low == mRows[i].high) {
1124                if (mRows[i].high < right) {
1125                    return true;
1126                }
1127            } else if (mRows[i].high < right - mMarginPrimary) {
1128                return true;
1129            }
1130        }
1131        return false;
1132    }
1133
1134    private boolean needsPrependVisibleItem() {
1135        if (mFirstVisiblePos > mFocusPosition) {
1136            return true;
1137        }
1138        for (int i = 0; i < mNumRows; i++) {
1139            if (mRows[i].low == mRows[i].high) {
1140                if (mRows[i].low > mScrollOffsetPrimary) {
1141                    return true;
1142                }
1143            } else if (mRows[i].low - mMarginPrimary > mScrollOffsetPrimary) {
1144                return true;
1145            }
1146        }
1147        return false;
1148    }
1149
1150    // Append one column if possible and return true if reach end.
1151    private boolean appendOneVisibleItem() {
1152        while (true) {
1153            if (mLastVisiblePos != NO_POSITION && mLastVisiblePos < mState.getItemCount() -1 &&
1154                    mLastVisiblePos < mGrid.getLastIndex()) {
1155                // append invisible view of saved location till last row
1156                final int index = mLastVisiblePos + 1;
1157                final int row = mGrid.getLocation(index).row;
1158                mGridProvider.createItem(index, row, true);
1159                if (row == mNumRows - 1) {
1160                    return false;
1161                }
1162            } else if ((mLastVisiblePos == NO_POSITION && mState.getItemCount() > 0) ||
1163                    (mLastVisiblePos != NO_POSITION &&
1164                            mLastVisiblePos < mState.getItemCount() - 1)) {
1165                mGrid.appendItems(mScrollOffsetPrimary + mSizePrimary);
1166                return false;
1167            } else {
1168                return true;
1169            }
1170        }
1171    }
1172
1173    private void appendVisibleItems() {
1174        while (needsAppendVisibleItem()) {
1175            if (appendOneVisibleItem()) {
1176                break;
1177            }
1178        }
1179    }
1180
1181    // Prepend one column if possible and return true if reach end.
1182    private boolean prependOneVisibleItem() {
1183        while (true) {
1184            if (mFirstVisiblePos > 0) {
1185                if (mFirstVisiblePos > mGrid.getFirstIndex()) {
1186                    // prepend invisible view of saved location till first row
1187                    final int index = mFirstVisiblePos - 1;
1188                    final int row = mGrid.getLocation(index).row;
1189                    mGridProvider.createItem(index, row, false);
1190                    if (row == 0) {
1191                        return false;
1192                    }
1193                } else {
1194                    mGrid.prependItems(mScrollOffsetPrimary);
1195                    return false;
1196                }
1197            } else {
1198                return true;
1199            }
1200        }
1201    }
1202
1203    private void prependVisibleItems() {
1204        while (needsPrependVisibleItem()) {
1205            if (prependOneVisibleItem()) {
1206                break;
1207            }
1208        }
1209    }
1210
1211    private void removeChildAt(int position) {
1212        View v = findViewByPosition(position);
1213        if (v != null) {
1214            if (DEBUG) {
1215                Log.d(getTag(), "removeAndRecycleViewAt " + position);
1216            }
1217            removeAndRecycleView(v, mRecycler);
1218        }
1219    }
1220
1221    private void removeInvisibleViewsAtEnd() {
1222        if (!mPruneChild) {
1223            return;
1224        }
1225        boolean update = false;
1226        while(mLastVisiblePos > mFirstVisiblePos && mLastVisiblePos > mFocusPosition) {
1227            View view = findViewByPosition(mLastVisiblePos);
1228            if (getViewMin(view) > mSizePrimary) {
1229                removeChildAt(mLastVisiblePos);
1230                mLastVisiblePos--;
1231                update = true;
1232            } else {
1233                break;
1234            }
1235        }
1236        if (update) {
1237            updateRowsMinMax();
1238        }
1239    }
1240
1241    private void removeInvisibleViewsAtFront() {
1242        if (!mPruneChild) {
1243            return;
1244        }
1245        boolean update = false;
1246        while(mLastVisiblePos > mFirstVisiblePos && mFirstVisiblePos < mFocusPosition) {
1247            View view = findViewByPosition(mFirstVisiblePos);
1248            if (getViewMax(view) < 0) {
1249                removeChildAt(mFirstVisiblePos);
1250                mFirstVisiblePos++;
1251                update = true;
1252            } else {
1253                break;
1254            }
1255        }
1256        if (update) {
1257            updateRowsMinMax();
1258        }
1259    }
1260
1261    private void updateRowsMinMax() {
1262        if (mFirstVisiblePos < 0) {
1263            return;
1264        }
1265        for (int i = 0; i < mNumRows; i++) {
1266            mRows[i].low = Integer.MAX_VALUE;
1267            mRows[i].high = Integer.MIN_VALUE;
1268        }
1269        for (int i = mFirstVisiblePos; i <= mLastVisiblePos; i++) {
1270            View view = findViewByPosition(i);
1271            int row = mGrid.getLocation(i).row;
1272            int low = getViewMin(view) + mScrollOffsetPrimary;
1273            if (low < mRows[row].low) {
1274                mRows[row].low = low;
1275            }
1276            int high = getViewMax(view) + mScrollOffsetPrimary;
1277            if (high > mRows[row].high) {
1278                mRows[row].high = high;
1279            }
1280        }
1281    }
1282
1283    // Fast layout when there is no structure change, adapter change, etc.
1284    protected void fastRelayout() {
1285        initScrollController();
1286
1287        List<Integer>[] rows = mGrid.getItemPositionsInRows(mFirstVisiblePos, mLastVisiblePos);
1288
1289        // relayout and repositioning views on each row
1290        for (int i = 0; i < mNumRows; i++) {
1291            List<Integer> row = rows[i];
1292            final int startSecondary = getRowStartSecondary(i) - mScrollOffsetSecondary;
1293            for (int j = 0, size = row.size(); j < size; j++) {
1294                final int position = row.get(j);
1295                final View view = findViewByPosition(position);
1296                int primaryDelta, start, end;
1297
1298                if (mOrientation == HORIZONTAL) {
1299                    final int primarySize = view.getMeasuredWidth();
1300                    if (view.isLayoutRequested()) {
1301                        measureChild(view, i);
1302                    }
1303                    start = getViewMin(view);
1304                    end = start + view.getMeasuredWidth();
1305                    primaryDelta = view.getMeasuredWidth() - primarySize;
1306                    if (primaryDelta != 0) {
1307                        for (int k = j + 1; k < size; k++) {
1308                            findViewByPosition(row.get(k)).offsetLeftAndRight(primaryDelta);
1309                        }
1310                    }
1311                } else {
1312                    final int primarySize = view.getMeasuredHeight();
1313                    if (view.isLayoutRequested()) {
1314                        measureChild(view, i);
1315                    }
1316                    start = getViewMin(view);
1317                    end = start + view.getMeasuredHeight();
1318                    primaryDelta = view.getMeasuredHeight() - primarySize;
1319                    if (primaryDelta != 0) {
1320                        for (int k = j + 1; k < size; k++) {
1321                            findViewByPosition(row.get(k)).offsetTopAndBottom(primaryDelta);
1322                        }
1323                    }
1324                }
1325                layoutChild(i, view, start, end, startSecondary);
1326            }
1327        }
1328
1329        updateRowsMinMax();
1330        appendVisibleItems();
1331        prependVisibleItems();
1332
1333        updateRowsMinMax();
1334        updateScrollMin();
1335        updateScrollMax();
1336        updateScrollSecondAxis();
1337
1338        if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
1339            View focusView = findViewByPosition(mFocusPosition == NO_POSITION ? 0 : mFocusPosition);
1340            scrollToView(focusView, false);
1341        }
1342    }
1343
1344    @Override
1345    public boolean supportsItemAnimations() {
1346        return mAnimateChildLayout;
1347    }
1348
1349    // Lays out items based on the current scroll position
1350    @Override
1351    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
1352        if (DEBUG) {
1353            Log.v(getTag(), "layoutChildren start numRows " + mNumRows + " mScrollOffsetSecondary "
1354                    + mScrollOffsetSecondary + " mScrollOffsetPrimary " + mScrollOffsetPrimary
1355                    + " inPreLayout " + state.isPreLayout()
1356                    + " didStructureChange " + state.didStructureChange()
1357                    + " mForceFullLayout " + mForceFullLayout);
1358            Log.v(getTag(), "width " + getWidth() + " height " + getHeight());
1359        }
1360
1361        if (mNumRows == 0) {
1362            // haven't done measure yet
1363            return;
1364        }
1365        final int itemCount = state.getItemCount();
1366        if (itemCount < 0) {
1367            return;
1368        }
1369
1370        if (!mLayoutEnabled) {
1371            discardLayoutInfo();
1372            removeAllViews();
1373            return;
1374        }
1375        mInLayout = true;
1376
1377        saveContext(recycler, state);
1378        // Track the old focus view so we can adjust our system scroll position
1379        // so that any scroll animations happening now will remain valid.
1380        // We must use same delta in Pre Layout (if prelayout exists) and second layout.
1381        // So we cache the deltas in PreLayout and use it in second layout.
1382        int delta = 0, deltaSecondary = 0;
1383        if (!state.isPreLayout() && mUseDeltaInPreLayout) {
1384            delta = mDeltaInPreLayout;
1385            deltaSecondary = mDeltaSecondaryInPreLayout;
1386        } else {
1387            if (mFocusPosition != NO_POSITION
1388                    && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
1389                View focusView = findViewByPosition(mFocusPosition);
1390                if (focusView != null) {
1391                    delta = mWindowAlignment.mainAxis().getSystemScrollPos(
1392                            getViewCenter(focusView) + mScrollOffsetPrimary) - mScrollOffsetPrimary;
1393                    deltaSecondary =
1394                        mWindowAlignment.secondAxis().getSystemScrollPos(
1395                                getViewCenterSecondary(focusView) + mScrollOffsetSecondary)
1396                        - mScrollOffsetSecondary;
1397                    if (mUseDeltaInPreLayout = state.isPreLayout()) {
1398                        mDeltaInPreLayout = delta;
1399                        mDeltaSecondaryInPreLayout = deltaSecondary;
1400                    }
1401                }
1402            }
1403        }
1404
1405        final boolean hasDoneFirstLayout = hasDoneFirstLayout();
1406        if (!mState.didStructureChange() && !mForceFullLayout && hasDoneFirstLayout) {
1407            fastRelayout();
1408        } else {
1409            boolean hadFocus = mBaseGridView.hasFocus();
1410
1411            int newFocusPosition = init(mFocusPosition);
1412            if (DEBUG) {
1413                Log.v(getTag(), "mFocusPosition " + mFocusPosition + " newFocusPosition "
1414                    + newFocusPosition);
1415            }
1416
1417            // depending on result of init(), either recreating everything
1418            // or try to reuse the row start positions near mFocusPosition
1419            if (mGrid.getSize() == 0) {
1420                // this is a fresh creating all items, starting from
1421                // mFocusPosition with a estimated row index.
1422                mGrid.setStart(newFocusPosition, StaggeredGrid.START_DEFAULT);
1423
1424                // Can't track the old focus view
1425                delta = deltaSecondary = 0;
1426
1427            } else {
1428                // mGrid remembers Locations for the column that
1429                // contains mFocusePosition and also mRows remembers start
1430                // positions of each row.
1431                // Manually re-create child views for that column
1432                int firstIndex = mGrid.getFirstIndex();
1433                int lastIndex = mGrid.getLastIndex();
1434                for (int i = firstIndex; i <= lastIndex; i++) {
1435                    mGridProvider.createItem(i, mGrid.getLocation(i).row, true);
1436                }
1437            }
1438            // add visible views at end until reach the end of window
1439            appendVisibleItems();
1440            // add visible views at front until reach the start of window
1441            prependVisibleItems();
1442            // multiple rounds: scrollToView of first round may drag first/last child into
1443            // "visible window" and we update scrollMin/scrollMax then run second scrollToView
1444            int oldFirstVisible;
1445            int oldLastVisible;
1446            do {
1447                oldFirstVisible = mFirstVisiblePos;
1448                oldLastVisible = mLastVisiblePos;
1449                View focusView = findViewByPosition(newFocusPosition);
1450                // we need force to initialize the child view's position
1451                scrollToView(focusView, false);
1452                if (focusView != null && hadFocus) {
1453                    focusView.requestFocus();
1454                }
1455                appendVisibleItems();
1456                prependVisibleItems();
1457                removeInvisibleViewsAtFront();
1458                removeInvisibleViewsAtEnd();
1459            } while (mFirstVisiblePos != oldFirstVisible || mLastVisiblePos != oldLastVisible);
1460        }
1461        mForceFullLayout = false;
1462
1463        if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
1464            scrollDirectionPrimary(-delta);
1465            scrollDirectionSecondary(-deltaSecondary);
1466        }
1467        appendVisibleItems();
1468        prependVisibleItems();
1469        removeInvisibleViewsAtFront();
1470        removeInvisibleViewsAtEnd();
1471
1472        if (DEBUG) {
1473            StringWriter sw = new StringWriter();
1474            PrintWriter pw = new PrintWriter(sw);
1475            mGrid.debugPrint(pw);
1476            Log.d(getTag(), sw.toString());
1477        }
1478
1479        if (mRowSecondarySizeRefresh) {
1480            mRowSecondarySizeRefresh = false;
1481        } else {
1482            updateRowSecondarySizeRefresh();
1483        }
1484
1485        if (!state.isPreLayout()) {
1486            mUseDeltaInPreLayout = false;
1487            if (!hasDoneFirstLayout) {
1488                dispatchChildSelected();
1489            }
1490        }
1491        mInLayout = false;
1492        leaveContext();
1493        if (DEBUG) Log.v(getTag(), "layoutChildren end");
1494    }
1495
1496    private void offsetChildrenSecondary(int increment) {
1497        final int childCount = getChildCount();
1498        if (mOrientation == HORIZONTAL) {
1499            for (int i = 0; i < childCount; i++) {
1500                getChildAt(i).offsetTopAndBottom(increment);
1501            }
1502        } else {
1503            for (int i = 0; i < childCount; i++) {
1504                getChildAt(i).offsetLeftAndRight(increment);
1505            }
1506        }
1507        mScrollOffsetSecondary -= increment;
1508    }
1509
1510    private void offsetChildrenPrimary(int increment) {
1511        final int childCount = getChildCount();
1512        if (mOrientation == VERTICAL) {
1513            for (int i = 0; i < childCount; i++) {
1514                getChildAt(i).offsetTopAndBottom(increment);
1515            }
1516        } else {
1517            for (int i = 0; i < childCount; i++) {
1518                getChildAt(i).offsetLeftAndRight(increment);
1519            }
1520        }
1521        mScrollOffsetPrimary -= increment;
1522    }
1523
1524    @Override
1525    public int scrollHorizontallyBy(int dx, Recycler recycler, RecyclerView.State state) {
1526        if (DEBUG) Log.v(getTag(), "scrollHorizontallyBy " + dx);
1527        if (!mLayoutEnabled) {
1528            return 0;
1529        }
1530        saveContext(recycler, state);
1531        int result;
1532        if (mOrientation == HORIZONTAL) {
1533            result = scrollDirectionPrimary(dx);
1534        } else {
1535            result = scrollDirectionSecondary(dx);
1536        }
1537        leaveContext();
1538        return result;
1539    }
1540
1541    @Override
1542    public int scrollVerticallyBy(int dy, Recycler recycler, RecyclerView.State state) {
1543        if (DEBUG) Log.v(getTag(), "scrollVerticallyBy " + dy);
1544        if (!mLayoutEnabled) {
1545            return 0;
1546        }
1547        saveContext(recycler, state);
1548        int result;
1549        if (mOrientation == VERTICAL) {
1550            result = scrollDirectionPrimary(dy);
1551        } else {
1552            result = scrollDirectionSecondary(dy);
1553        }
1554        leaveContext();
1555        return result;
1556    }
1557
1558    // scroll in main direction may add/prune views
1559    private int scrollDirectionPrimary(int da) {
1560        if (da == 0) {
1561            return 0;
1562        }
1563        offsetChildrenPrimary(-da);
1564        if (mInLayout) {
1565            return da;
1566        }
1567
1568        int childCount = getChildCount();
1569        boolean updated;
1570
1571        if (da > 0) {
1572            appendVisibleItems();
1573        } else if (da < 0) {
1574            prependVisibleItems();
1575        }
1576        updated = getChildCount() > childCount;
1577        childCount = getChildCount();
1578
1579        if (da > 0) {
1580            removeInvisibleViewsAtFront();
1581        } else if (da < 0) {
1582            removeInvisibleViewsAtEnd();
1583        }
1584        updated |= getChildCount() < childCount;
1585
1586        if (updated) {
1587            updateRowSecondarySizeRefresh();
1588        }
1589
1590        mBaseGridView.invalidate();
1591        return da;
1592    }
1593
1594    // scroll in second direction will not add/prune views
1595    private int scrollDirectionSecondary(int dy) {
1596        if (dy == 0) {
1597            return 0;
1598        }
1599        offsetChildrenSecondary(-dy);
1600        mBaseGridView.invalidate();
1601        return dy;
1602    }
1603
1604    private void updateScrollMax() {
1605        if (mLastVisiblePos >= 0 && mLastVisiblePos == mState.getItemCount() - 1) {
1606            int maxEdge = Integer.MIN_VALUE;
1607            for (int i = 0; i < mRows.length; i++) {
1608                if (mRows[i].high > maxEdge) {
1609                    maxEdge = mRows[i].high;
1610                }
1611            }
1612            mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1613            if (DEBUG) Log.v(getTag(), "updating scroll maxEdge to " + maxEdge);
1614        }
1615    }
1616
1617    private void updateScrollMin() {
1618        if (mFirstVisiblePos == 0) {
1619            int minEdge = Integer.MAX_VALUE;
1620            for (int i = 0; i < mRows.length; i++) {
1621                if (mRows[i].low < minEdge) {
1622                    minEdge = mRows[i].low;
1623                }
1624            }
1625            mWindowAlignment.mainAxis().setMinEdge(minEdge);
1626            if (DEBUG) Log.v(getTag(), "updating scroll minEdge to " + minEdge);
1627        }
1628    }
1629
1630    private void updateScrollSecondAxis() {
1631        mWindowAlignment.secondAxis().setMinEdge(0);
1632        mWindowAlignment.secondAxis().setMaxEdge(getSizeSecondary());
1633    }
1634
1635    private void initScrollController() {
1636        mWindowAlignment.horizontal.setSize(getWidth());
1637        mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight());
1638        mWindowAlignment.vertical.setSize(getHeight());
1639        mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom());
1640        mSizePrimary = mWindowAlignment.mainAxis().getSize();
1641        mWindowAlignment.mainAxis().invalidateScrollMin();
1642        mWindowAlignment.mainAxis().invalidateScrollMax();
1643
1644        if (DEBUG) {
1645            Log.v(getTag(), "initScrollController mSizePrimary " + mSizePrimary
1646                    + " mWindowAlignment " + mWindowAlignment);
1647        }
1648    }
1649
1650    public void setSelection(RecyclerView parent, int position) {
1651        setSelection(parent, position, false);
1652    }
1653
1654    public void setSelectionSmooth(RecyclerView parent, int position) {
1655        setSelection(parent, position, true);
1656    }
1657
1658    public int getSelection() {
1659        return mFocusPosition;
1660    }
1661
1662    public void setSelection(RecyclerView parent, int position, boolean smooth) {
1663        if (mFocusPosition == position) {
1664            return;
1665        }
1666        View view = findViewByPosition(position);
1667        if (view != null) {
1668            scrollToView(view, smooth);
1669        } else {
1670            mFocusPosition = position;
1671            if (!mLayoutEnabled) {
1672                return;
1673            }
1674            if (smooth) {
1675                if (!hasDoneFirstLayout()) {
1676                    Log.w(getTag(), "setSelectionSmooth should " +
1677                            "not be called before first layout pass");
1678                    return;
1679                }
1680                LinearSmoothScroller linearSmoothScroller =
1681                        new LinearSmoothScroller(parent.getContext()) {
1682                    @Override
1683                    public PointF computeScrollVectorForPosition(int targetPosition) {
1684                        if (getChildCount() == 0) {
1685                            return null;
1686                        }
1687                        final int firstChildPos = getPosition(getChildAt(0));
1688                        final int direction = targetPosition < firstChildPos ? -1 : 1;
1689                        if (mOrientation == HORIZONTAL) {
1690                            return new PointF(direction, 0);
1691                        } else {
1692                            return new PointF(0, direction);
1693                        }
1694                    }
1695                    @Override
1696                    protected void onTargetFound(View targetView,
1697                            RecyclerView.State state, Action action) {
1698                        if (hasFocus()) {
1699                            targetView.requestFocus();
1700                        }
1701                        if (updateScrollPosition(targetView, false, mTempDeltas)) {
1702                            int dx, dy;
1703                            if (mOrientation == HORIZONTAL) {
1704                                dx = mTempDeltas[0];
1705                                dy = mTempDeltas[1];
1706                            } else {
1707                                dx = mTempDeltas[1];
1708                                dy = mTempDeltas[0];
1709                            }
1710                            final int distance = (int) Math.sqrt(dx * dx + dy * dy);
1711                            final int time = calculateTimeForDeceleration(distance);
1712                            action.update(dx, dy, time, mDecelerateInterpolator);
1713                        }
1714                    }
1715                };
1716                linearSmoothScroller.setTargetPosition(position);
1717                startSmoothScroll(linearSmoothScroller);
1718            } else {
1719                mForceFullLayout = true;
1720                parent.requestLayout();
1721            }
1722        }
1723    }
1724
1725    @Override
1726    public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
1727        boolean needsLayout = false;
1728        if (itemCount != 0) {
1729            if (mFirstVisiblePos < 0) {
1730                needsLayout = true;
1731            } else if (!(positionStart > mLastVisiblePos + 1 ||
1732                    positionStart + itemCount < mFirstVisiblePos - 1)) {
1733                needsLayout = true;
1734            }
1735        }
1736        if (needsLayout) {
1737            recyclerView.requestLayout();
1738        }
1739    }
1740
1741    @Override
1742    public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) {
1743        if (mFocusSearchDisabled) {
1744            return true;
1745        }
1746        if (!mInLayout) {
1747            scrollToView(child, true);
1748        }
1749        return true;
1750    }
1751
1752    @Override
1753    public boolean requestChildRectangleOnScreen(RecyclerView parent, View view, Rect rect,
1754            boolean immediate) {
1755        if (DEBUG) Log.v(getTag(), "requestChildRectangleOnScreen " + view + " " + rect);
1756        return false;
1757    }
1758
1759    int getScrollOffsetX() {
1760        return mOrientation == HORIZONTAL ? mScrollOffsetPrimary : mScrollOffsetSecondary;
1761    }
1762
1763    int getScrollOffsetY() {
1764        return mOrientation == HORIZONTAL ? mScrollOffsetSecondary : mScrollOffsetPrimary;
1765    }
1766
1767    public void getViewSelectedOffsets(View view, int[] offsets) {
1768        int scrollOffsetX = getScrollOffsetX();
1769        int scrollOffsetY = getScrollOffsetY();
1770        int viewCenterX = scrollOffsetX + getViewCenterX(view);
1771        int viewCenterY = scrollOffsetY + getViewCenterY(view);
1772        offsets[0] = mWindowAlignment.horizontal.getSystemScrollPos(viewCenterX) - scrollOffsetX;
1773        offsets[1] = mWindowAlignment.vertical.getSystemScrollPos(viewCenterY) - scrollOffsetY;
1774    }
1775
1776    /**
1777     * Scroll to a given child view and change mFocusPosition.
1778     */
1779    private void scrollToView(View view, boolean smooth) {
1780        int newFocusPosition = getPositionByView(view);
1781        if (mInLayout || newFocusPosition != mFocusPosition) {
1782            mFocusPosition = newFocusPosition;
1783            dispatchChildSelected();
1784        }
1785        if (mBaseGridView.isChildrenDrawingOrderEnabledInternal()) {
1786            mBaseGridView.invalidate();
1787        }
1788        if (view == null) {
1789            return;
1790        }
1791        if (!view.hasFocus() && mBaseGridView.hasFocus()) {
1792            // transfer focus to the child if it does not have focus yet (e.g. triggered
1793            // by setSelection())
1794            view.requestFocus();
1795        }
1796        if (updateScrollPosition(view, mInLayout, mTempDeltas)) {
1797            scrollGrid(mTempDeltas[0], mTempDeltas[1], smooth);
1798        }
1799    }
1800
1801    private boolean updateScrollPosition(View view, boolean force, int[] deltas) {
1802        switch (mFocusScrollStrategy) {
1803        case BaseGridView.FOCUS_SCROLL_ALIGNED:
1804        default:
1805            return updateAlignedPosition(view, force, deltas);
1806        case BaseGridView.FOCUS_SCROLL_ITEM:
1807        case BaseGridView.FOCUS_SCROLL_PAGE:
1808            return updateNoneAlignedPosition(view, deltas);
1809        }
1810    }
1811
1812    private boolean updateNoneAlignedPosition(View view, int[] deltas) {
1813        int pos = getPositionByView(view);
1814        int viewMin = getViewMin(view);
1815        int viewMax = getViewMax(view);
1816        // we either align "firstView" to left/top padding edge
1817        // or align "lastView" to right/bottom padding edge
1818        View firstView = null;
1819        View lastView = null;
1820        int paddingLow = mWindowAlignment.mainAxis().getPaddingLow();
1821        int clientSize = mWindowAlignment.mainAxis().getClientSize();
1822        final int row = mGrid.getLocation(pos).row;
1823        if (viewMin < paddingLow) {
1824            // view enters low padding area:
1825            firstView = view;
1826            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
1827                // scroll one "page" left/top,
1828                // align first visible item of the "page" at the low padding edge.
1829                while (!prependOneVisibleItem()) {
1830                    List<Integer> positions =
1831                            mGrid.getItemPositionsInRows(mFirstVisiblePos, pos)[row];
1832                    firstView = findViewByPosition(positions.get(0));
1833                    if (viewMax - getViewMin(firstView) > clientSize) {
1834                        if (positions.size() > 1) {
1835                            firstView = findViewByPosition(positions.get(1));
1836                        }
1837                        break;
1838                    }
1839                }
1840            }
1841        } else if (viewMax > clientSize + paddingLow) {
1842            // view enters high padding area:
1843            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
1844                // scroll whole one page right/bottom, align view at the low padding edge.
1845                firstView = view;
1846                do {
1847                    List<Integer> positions =
1848                            mGrid.getItemPositionsInRows(pos, mLastVisiblePos)[row];
1849                    lastView = findViewByPosition(positions.get(positions.size() - 1));
1850                    if (getViewMax(lastView) - viewMin > clientSize) {
1851                        lastView = null;
1852                        break;
1853                    }
1854                } while (!appendOneVisibleItem());
1855                if (lastView != null) {
1856                    // however if we reached end,  we should align last view.
1857                    firstView = null;
1858                }
1859            } else {
1860                lastView = view;
1861            }
1862        }
1863        int scrollPrimary = 0;
1864        int scrollSecondary = 0;
1865        if (firstView != null) {
1866            scrollPrimary = getViewMin(firstView) - paddingLow;
1867        } else if (lastView != null) {
1868            scrollPrimary = getViewMax(lastView) - (paddingLow + clientSize);
1869        }
1870        View secondaryAlignedView;
1871        if (firstView != null) {
1872            secondaryAlignedView = firstView;
1873        } else if (lastView != null) {
1874            secondaryAlignedView = lastView;
1875        } else {
1876            secondaryAlignedView = view;
1877        }
1878        int viewCenterSecondary = mScrollOffsetSecondary +
1879                getViewCenterSecondary(secondaryAlignedView);
1880        mWindowAlignment.secondAxis().updateScrollCenter(viewCenterSecondary);
1881        scrollSecondary = mWindowAlignment.secondAxis().getSystemScrollPos();
1882        scrollSecondary -= mScrollOffsetSecondary;
1883        if (scrollPrimary != 0 || scrollSecondary != 0) {
1884            deltas[0] = scrollPrimary;
1885            deltas[1] = scrollSecondary;
1886            return true;
1887        }
1888        return false;
1889    }
1890
1891    private boolean updateAlignedPosition(View view, boolean force, int[] deltas) {
1892        int viewCenterPrimary = mScrollOffsetPrimary + getViewCenter(view);
1893        int viewCenterSecondary = mScrollOffsetSecondary + getViewCenterSecondary(view);
1894
1895        if (force || viewCenterPrimary != mWindowAlignment.mainAxis().getScrollCenter()
1896                || viewCenterSecondary != mWindowAlignment.secondAxis().getScrollCenter()) {
1897            mWindowAlignment.mainAxis().updateScrollCenter(viewCenterPrimary);
1898            mWindowAlignment.secondAxis().updateScrollCenter(viewCenterSecondary);
1899            int scrollPrimary = mWindowAlignment.mainAxis().getSystemScrollPos();
1900            int scrollSecondary = mWindowAlignment.secondAxis().getSystemScrollPos();
1901            if (DEBUG) {
1902                Log.v(getTag(), "updateAlignedPosition " + scrollPrimary + " " + scrollSecondary
1903                        +" " + mWindowAlignment);
1904            }
1905            scrollPrimary -= mScrollOffsetPrimary;
1906            scrollSecondary -= mScrollOffsetSecondary;
1907            deltas[0] = scrollPrimary;
1908            deltas[1] = scrollSecondary;
1909            return true;
1910        }
1911        return false;
1912    }
1913
1914    private void scrollGrid(int scrollPrimary, int scrollSecondary, boolean smooth) {
1915        if (mInLayout) {
1916            scrollDirectionPrimary(scrollPrimary);
1917            scrollDirectionSecondary(scrollSecondary);
1918        } else {
1919            int scrollX;
1920            int scrollY;
1921            if (mOrientation == HORIZONTAL) {
1922                scrollX = scrollPrimary;
1923                scrollY = scrollSecondary;
1924            } else {
1925                scrollX = scrollSecondary;
1926                scrollY = scrollPrimary;
1927            }
1928            if (smooth) {
1929                mBaseGridView.smoothScrollBy(scrollX, scrollY);
1930            } else {
1931                mBaseGridView.scrollBy(scrollX, scrollY);
1932            }
1933        }
1934    }
1935
1936    public void setAnimateChildLayout(boolean animateChildLayout) {
1937        mAnimateChildLayout = animateChildLayout;
1938    }
1939
1940    public boolean isChildLayoutAnimated() {
1941        return mAnimateChildLayout;
1942    }
1943
1944    public void setPruneChild(boolean pruneChild) {
1945        if (mPruneChild != pruneChild) {
1946            mPruneChild = pruneChild;
1947            if (mPruneChild) {
1948                requestLayout();
1949            }
1950        }
1951    }
1952
1953    public boolean getPruneChild() {
1954        return mPruneChild;
1955    }
1956
1957    private int findImmediateChildIndex(View view) {
1958        while (view != null && view != mBaseGridView) {
1959            int index = mBaseGridView.indexOfChild(view);
1960            if (index >= 0) {
1961                return index;
1962            }
1963            view = (View) view.getParent();
1964        }
1965        return NO_POSITION;
1966    }
1967
1968    void setFocusSearchDisabled(boolean disabled) {
1969        mFocusSearchDisabled = disabled;
1970    }
1971
1972    boolean isFocusSearchDisabled() {
1973        return mFocusSearchDisabled;
1974    }
1975
1976    @Override
1977    public View onInterceptFocusSearch(View focused, int direction) {
1978        if (mFocusSearchDisabled) {
1979            return focused;
1980        }
1981        return null;
1982    }
1983
1984    boolean hasNextViewInSameRow(int pos) {
1985        if (mGrid == null || pos == NO_POSITION) {
1986            return false;
1987        }
1988        final int focusedRow = mGrid.getLocation(pos).row;
1989        for (int i = 0, count = getChildCount(); i < count; i++) {
1990            int position = getPositionByIndex(i);
1991            StaggeredGrid.Location loc = mGrid.getLocation(position);
1992            if (loc != null && loc.row == focusedRow) {
1993                if (position > pos) {
1994                    return true;
1995                }
1996            }
1997        }
1998        return false;
1999    }
2000
2001    boolean hasPreviousViewInSameRow(int pos) {
2002        if (mGrid == null || pos == NO_POSITION) {
2003            return false;
2004        }
2005        final int focusedRow = mGrid.getLocation(pos).row;
2006        for (int i = getChildCount() - 1; i >= 0; i--) {
2007            int position = getPositionByIndex(i);
2008            StaggeredGrid.Location loc = mGrid.getLocation(position);
2009            if (loc != null && loc.row == focusedRow) {
2010                if (position < pos) {
2011                    return true;
2012                }
2013            }
2014        }
2015        return false;
2016    }
2017
2018    @Override
2019    public boolean onAddFocusables(RecyclerView recyclerView,
2020            ArrayList<View> views, int direction, int focusableMode) {
2021        if (mFocusSearchDisabled) {
2022            return true;
2023        }
2024        // If this viewgroup or one of its children currently has focus then we
2025        // consider our children for focus searching in main direction on the same row.
2026        // If this viewgroup has no focus and using focus align, we want the system
2027        // to ignore our children and pass focus to the viewgroup, which will pass
2028        // focus on to its children appropriately.
2029        // If this viewgroup has no focus and not using focus align, we want to
2030        // consider the child that does not overlap with padding area.
2031        if (recyclerView.hasFocus()) {
2032            final int movement = getMovement(direction);
2033            if (movement != PREV_ITEM && movement != NEXT_ITEM) {
2034                // Move on secondary direction uses default addFocusables().
2035                return false;
2036            }
2037            final View focused = recyclerView.findFocus();
2038            final int focusedPos = getPositionByIndex(findImmediateChildIndex(focused));
2039            // Add focusables of focused item.
2040            if (focusedPos != NO_POSITION) {
2041                findViewByPosition(focusedPos).addFocusables(views,  direction, focusableMode);
2042            }
2043            final int focusedRow = mGrid != null && focusedPos != NO_POSITION ?
2044                    mGrid.getLocation(focusedPos).row : NO_POSITION;
2045            // Add focusables of next neighbor of same row on the focus search direction.
2046            if (mGrid != null) {
2047                final int focusableCount = views.size();
2048                for (int i = 0, count = getChildCount(); i < count; i++) {
2049                    int index = movement == NEXT_ITEM ? i : count - 1 - i;
2050                    final View child = getChildAt(index);
2051                    if (child.getVisibility() != View.VISIBLE) {
2052                        continue;
2053                    }
2054                    int position = getPositionByIndex(index);
2055                    StaggeredGrid.Location loc = mGrid.getLocation(position);
2056                    if (focusedRow == NO_POSITION || (loc != null && loc.row == focusedRow)) {
2057                        if (focusedPos == NO_POSITION ||
2058                                (movement == NEXT_ITEM && position > focusedPos)
2059                                || (movement == PREV_ITEM && position < focusedPos)) {
2060                            child.addFocusables(views,  direction, focusableMode);
2061                            if (views.size() > focusableCount) {
2062                                break;
2063                            }
2064                        }
2065                    }
2066                }
2067            }
2068        } else {
2069            if (mFocusScrollStrategy != BaseGridView.FOCUS_SCROLL_ALIGNED) {
2070                // adding views not overlapping padding area to avoid scrolling in gaining focus
2071                int left = mWindowAlignment.mainAxis().getPaddingLow();
2072                int right = mWindowAlignment.mainAxis().getClientSize() + left;
2073                int focusableCount = views.size();
2074                for (int i = 0, count = getChildCount(); i < count; i++) {
2075                    View child = getChildAt(i);
2076                    if (child.getVisibility() == View.VISIBLE) {
2077                        if (getViewMin(child) >= left && getViewMax(child) <= right) {
2078                            child.addFocusables(views, direction, focusableMode);
2079                        }
2080                    }
2081                }
2082                // if we cannot find any, then just add all children.
2083                if (views.size() == focusableCount) {
2084                    for (int i = 0, count = getChildCount(); i < count; i++) {
2085                        View child = getChildAt(i);
2086                        if (child.getVisibility() == View.VISIBLE) {
2087                            child.addFocusables(views, direction, focusableMode);
2088                        }
2089                    }
2090                    if (views.size() != focusableCount) {
2091                        return true;
2092                    }
2093                } else {
2094                    return true;
2095                }
2096                // if still cannot find any, fall through and add itself
2097            }
2098            if (recyclerView.isFocusable()) {
2099                views.add(recyclerView);
2100            }
2101        }
2102        return true;
2103    }
2104
2105    @Override
2106    public View onFocusSearchFailed(View focused, int direction, Recycler recycler,
2107            RecyclerView.State state) {
2108        if (DEBUG) Log.v(getTag(), "onFocusSearchFailed direction " + direction);
2109
2110        saveContext(recycler, state);
2111        View view = null;
2112        int movement = getMovement(direction);
2113        final FocusFinder ff = FocusFinder.getInstance();
2114        if (movement == NEXT_ITEM) {
2115            while (view == null && !appendOneVisibleItem()) {
2116                view = ff.findNextFocus(mBaseGridView, focused, direction);
2117            }
2118        } else if (movement == PREV_ITEM){
2119            while (view == null && !prependOneVisibleItem()) {
2120                view = ff.findNextFocus(mBaseGridView, focused, direction);
2121            }
2122        }
2123        if (view == null) {
2124            // returning the same view to prevent focus lost when scrolling past the end of the list
2125            if (movement == PREV_ITEM) {
2126                view = mFocusOutFront ? null : focused;
2127            } else if (movement == NEXT_ITEM){
2128                view = mFocusOutEnd ? null : focused;
2129            }
2130        }
2131        leaveContext();
2132        if (DEBUG) Log.v(getTag(), "returning view " + view);
2133        return view;
2134    }
2135
2136    boolean gridOnRequestFocusInDescendants(RecyclerView recyclerView, int direction,
2137            Rect previouslyFocusedRect) {
2138        switch (mFocusScrollStrategy) {
2139        case BaseGridView.FOCUS_SCROLL_ALIGNED:
2140        default:
2141            return gridOnRequestFocusInDescendantsAligned(recyclerView,
2142                    direction, previouslyFocusedRect);
2143        case BaseGridView.FOCUS_SCROLL_PAGE:
2144        case BaseGridView.FOCUS_SCROLL_ITEM:
2145            return gridOnRequestFocusInDescendantsUnaligned(recyclerView,
2146                    direction, previouslyFocusedRect);
2147        }
2148    }
2149
2150    private boolean gridOnRequestFocusInDescendantsAligned(RecyclerView recyclerView,
2151            int direction, Rect previouslyFocusedRect) {
2152        View view = findViewByPosition(mFocusPosition);
2153        if (view != null) {
2154            boolean result = view.requestFocus(direction, previouslyFocusedRect);
2155            if (!result && DEBUG) {
2156                Log.w(getTag(), "failed to request focus on " + view);
2157            }
2158            return result;
2159        }
2160        return false;
2161    }
2162
2163    private boolean gridOnRequestFocusInDescendantsUnaligned(RecyclerView recyclerView,
2164            int direction, Rect previouslyFocusedRect) {
2165        // focus to view not overlapping padding area to avoid scrolling in gaining focus
2166        int index;
2167        int increment;
2168        int end;
2169        int count = getChildCount();
2170        if ((direction & View.FOCUS_FORWARD) != 0) {
2171            index = 0;
2172            increment = 1;
2173            end = count;
2174        } else {
2175            index = count - 1;
2176            increment = -1;
2177            end = -1;
2178        }
2179        int left = mWindowAlignment.mainAxis().getPaddingLow();
2180        int right = mWindowAlignment.mainAxis().getClientSize() + left;
2181        for (int i = index; i != end; i += increment) {
2182            View child = getChildAt(i);
2183            if (child.getVisibility() == View.VISIBLE) {
2184                if (getViewMin(child) >= left && getViewMax(child) <= right) {
2185                    if (child.requestFocus(direction, previouslyFocusedRect)) {
2186                        return true;
2187                    }
2188                }
2189            }
2190        }
2191        return false;
2192    }
2193
2194    private final static int PREV_ITEM = 0;
2195    private final static int NEXT_ITEM = 1;
2196    private final static int PREV_ROW = 2;
2197    private final static int NEXT_ROW = 3;
2198
2199    private int getMovement(int direction) {
2200        int movement = View.FOCUS_LEFT;
2201
2202        if (mOrientation == HORIZONTAL) {
2203            switch(direction) {
2204                case View.FOCUS_LEFT:
2205                    movement = PREV_ITEM;
2206                    break;
2207                case View.FOCUS_RIGHT:
2208                    movement = NEXT_ITEM;
2209                    break;
2210                case View.FOCUS_UP:
2211                    movement = PREV_ROW;
2212                    break;
2213                case View.FOCUS_DOWN:
2214                    movement = NEXT_ROW;
2215                    break;
2216            }
2217         } else if (mOrientation == VERTICAL) {
2218             switch(direction) {
2219                 case View.FOCUS_LEFT:
2220                     movement = PREV_ROW;
2221                     break;
2222                 case View.FOCUS_RIGHT:
2223                     movement = NEXT_ROW;
2224                     break;
2225                 case View.FOCUS_UP:
2226                     movement = PREV_ITEM;
2227                     break;
2228                 case View.FOCUS_DOWN:
2229                     movement = NEXT_ITEM;
2230                     break;
2231             }
2232         }
2233
2234        return movement;
2235    }
2236
2237    int getChildDrawingOrder(RecyclerView recyclerView, int childCount, int i) {
2238        View view = findViewByPosition(mFocusPosition);
2239        if (view == null) {
2240            return i;
2241        }
2242        int focusIndex = recyclerView.indexOfChild(view);
2243        // supposely 0 1 2 3 4 5 6 7 8 9, 4 is the center item
2244        // drawing order is 0 1 2 3 9 8 7 6 5 4
2245        if (i < focusIndex) {
2246            return i;
2247        } else if (i < childCount - 1) {
2248            return focusIndex + childCount - 1 - i;
2249        } else {
2250            return focusIndex;
2251        }
2252    }
2253
2254    @Override
2255    public void onAdapterChanged(RecyclerView.Adapter oldAdapter,
2256            RecyclerView.Adapter newAdapter) {
2257        discardLayoutInfo();
2258        super.onAdapterChanged(oldAdapter, newAdapter);
2259    }
2260
2261    private void discardLayoutInfo() {
2262        mGrid = null;
2263        mRows = null;
2264        mRowSizeSecondary = null;
2265        mFirstVisiblePos = -1;
2266        mLastVisiblePos = -1;
2267        mRowSecondarySizeRefresh = false;
2268    }
2269
2270    public void setLayoutEnabled(boolean layoutEnabled) {
2271        if (mLayoutEnabled != layoutEnabled) {
2272            mLayoutEnabled = layoutEnabled;
2273            requestLayout();
2274        }
2275    }
2276}
2277