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