GridLayoutManager.java revision e692c096892075c6ac5cf509f118df6b618edecc
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(boolean scrollToFocus) {
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 (scrollToFocus) {
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        final boolean scrollToFocus = !isSmoothScrolling()
1428                && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED;
1429        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
1430            mFocusPosition = mFocusPosition + mFocusPositionOffset;
1431            mFocusPositionOffset = 0;
1432        }
1433        saveContext(recycler, state);
1434        // Track the old focus view so we can adjust our system scroll position
1435        // so that any scroll animations happening now will remain valid.
1436        // We must use same delta in Pre Layout (if prelayout exists) and second layout.
1437        // So we cache the deltas in PreLayout and use it in second layout.
1438        int delta = 0, deltaSecondary = 0;
1439        if (mFocusPosition != NO_POSITION && scrollToFocus) {
1440            // FIXME: we should get the remaining scroll animation offset from RecyclerView
1441            View focusView = findViewByPosition(mFocusPosition);
1442            if (focusView != null) {
1443                delta = mWindowAlignment.mainAxis().getSystemScrollPos(mScrollOffsetPrimary
1444                        + getViewCenter(focusView), false, false) - mScrollOffsetPrimary;
1445                deltaSecondary = mWindowAlignment.secondAxis().getSystemScrollPos(
1446                        mScrollOffsetSecondary + getViewCenterSecondary(focusView),
1447                        false, false) - mScrollOffsetSecondary;
1448            }
1449        }
1450
1451        final boolean hasDoneFirstLayout = hasDoneFirstLayout();
1452        int savedFocusPos = mFocusPosition;
1453        boolean fastRelayout = false;
1454        if (!mState.didStructureChange() && !mForceFullLayout && hasDoneFirstLayout) {
1455            fastRelayout = true;
1456            fastRelayout(scrollToFocus);
1457        } else {
1458            boolean hadFocus = mBaseGridView.hasFocus();
1459
1460            int newFocusPosition = init(mFocusPosition);
1461            if (DEBUG) {
1462                Log.v(getTag(), "mFocusPosition " + mFocusPosition + " newFocusPosition "
1463                    + newFocusPosition);
1464            }
1465
1466            // depending on result of init(), either recreating everything
1467            // or try to reuse the row start positions near mFocusPosition
1468            if (mGrid.getSize() == 0) {
1469                // this is a fresh creating all items, starting from
1470                // mFocusPosition with a estimated row index.
1471                mGrid.setStart(newFocusPosition, StaggeredGrid.START_DEFAULT);
1472
1473                // Can't track the old focus view
1474                delta = deltaSecondary = 0;
1475
1476            } else {
1477                // mGrid remembers Locations for the column that
1478                // contains mFocusePosition and also mRows remembers start
1479                // positions of each row.
1480                // Manually re-create child views for that column
1481                int firstIndex = mGrid.getFirstIndex();
1482                int lastIndex = mGrid.getLastIndex();
1483                for (int i = firstIndex; i <= lastIndex; i++) {
1484                    mGridProvider.createItem(i, mGrid.getLocation(i).row, true);
1485                }
1486            }
1487            // add visible views at end until reach the end of window
1488            appendVisibleItems();
1489            // add visible views at front until reach the start of window
1490            prependVisibleItems();
1491            // multiple rounds: scrollToView of first round may drag first/last child into
1492            // "visible window" and we update scrollMin/scrollMax then run second scrollToView
1493            int oldFirstVisible;
1494            int oldLastVisible;
1495            do {
1496                updateScrollMin();
1497                updateScrollMax();
1498                oldFirstVisible = mFirstVisiblePos;
1499                oldLastVisible = mLastVisiblePos;
1500                View focusView = findViewByPosition(newFocusPosition);
1501                // we need force to initialize the child view's position
1502                scrollToView(focusView, false);
1503                if (focusView != null && hadFocus) {
1504                    focusView.requestFocus();
1505                }
1506                appendVisibleItems();
1507                prependVisibleItems();
1508                removeInvisibleViewsAtFront();
1509                removeInvisibleViewsAtEnd();
1510            } while (mFirstVisiblePos != oldFirstVisible || mLastVisiblePos != oldLastVisible);
1511        }
1512        mForceFullLayout = false;
1513
1514        if (scrollToFocus) {
1515            scrollDirectionPrimary(-delta);
1516            scrollDirectionSecondary(-deltaSecondary);
1517        }
1518        appendVisibleItems();
1519        prependVisibleItems();
1520        removeInvisibleViewsAtFront();
1521        removeInvisibleViewsAtEnd();
1522
1523        if (DEBUG) {
1524            StringWriter sw = new StringWriter();
1525            PrintWriter pw = new PrintWriter(sw);
1526            mGrid.debugPrint(pw);
1527            Log.d(getTag(), sw.toString());
1528        }
1529
1530        if (mRowSecondarySizeRefresh) {
1531            mRowSecondarySizeRefresh = false;
1532        } else {
1533            updateRowSecondarySizeRefresh();
1534        }
1535
1536        if (!fastRelayout || mFocusPosition != savedFocusPos) {
1537            dispatchChildSelected();
1538        }
1539        mInLayout = false;
1540        leaveContext();
1541        if (DEBUG) Log.v(getTag(), "layoutChildren end");
1542    }
1543
1544    private void offsetChildrenSecondary(int increment) {
1545        final int childCount = getChildCount();
1546        if (mOrientation == HORIZONTAL) {
1547            for (int i = 0; i < childCount; i++) {
1548                getChildAt(i).offsetTopAndBottom(increment);
1549            }
1550        } else {
1551            for (int i = 0; i < childCount; i++) {
1552                getChildAt(i).offsetLeftAndRight(increment);
1553            }
1554        }
1555    }
1556
1557    private void offsetChildrenPrimary(int increment) {
1558        final int childCount = getChildCount();
1559        if (mOrientation == VERTICAL) {
1560            for (int i = 0; i < childCount; i++) {
1561                getChildAt(i).offsetTopAndBottom(increment);
1562            }
1563        } else {
1564            for (int i = 0; i < childCount; i++) {
1565                getChildAt(i).offsetLeftAndRight(increment);
1566            }
1567        }
1568    }
1569
1570    @Override
1571    public int scrollHorizontallyBy(int dx, Recycler recycler, RecyclerView.State state) {
1572        if (DEBUG) Log.v(getTag(), "scrollHorizontallyBy " + dx);
1573        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1574            return 0;
1575        }
1576        saveContext(recycler, state);
1577        int result;
1578        if (mOrientation == HORIZONTAL) {
1579            result = scrollDirectionPrimary(dx);
1580        } else {
1581            result = scrollDirectionSecondary(dx);
1582        }
1583        leaveContext();
1584        return result;
1585    }
1586
1587    @Override
1588    public int scrollVerticallyBy(int dy, Recycler recycler, RecyclerView.State state) {
1589        if (DEBUG) Log.v(getTag(), "scrollVerticallyBy " + dy);
1590        if (!mLayoutEnabled || !hasDoneFirstLayout()) {
1591            return 0;
1592        }
1593        saveContext(recycler, state);
1594        int result;
1595        if (mOrientation == VERTICAL) {
1596            result = scrollDirectionPrimary(dy);
1597        } else {
1598            result = scrollDirectionSecondary(dy);
1599        }
1600        leaveContext();
1601        return result;
1602    }
1603
1604    // scroll in main direction may add/prune views
1605    private int scrollDirectionPrimary(int da) {
1606        if (da > 0) {
1607            if (!mWindowAlignment.mainAxis().isMaxUnknown()) {
1608                int maxScroll = mWindowAlignment.mainAxis().getMaxScroll();
1609                if (mScrollOffsetPrimary + da > maxScroll) {
1610                    da = maxScroll - mScrollOffsetPrimary;
1611                }
1612            }
1613        } else if (da < 0) {
1614            if (!mWindowAlignment.mainAxis().isMinUnknown()) {
1615                int minScroll = mWindowAlignment.mainAxis().getMinScroll();
1616                if (mScrollOffsetPrimary + da < minScroll) {
1617                    da = minScroll - mScrollOffsetPrimary;
1618                }
1619            }
1620        }
1621        if (da == 0) {
1622            return 0;
1623        }
1624        offsetChildrenPrimary(-da);
1625        mScrollOffsetPrimary += da;
1626        if (mInLayout) {
1627            return da;
1628        }
1629
1630        int childCount = getChildCount();
1631        boolean updated;
1632
1633        if (da > 0) {
1634            appendVisibleItems();
1635        } else if (da < 0) {
1636            prependVisibleItems();
1637        }
1638        updated = getChildCount() > childCount;
1639        childCount = getChildCount();
1640
1641        if (da > 0) {
1642            removeInvisibleViewsAtFront();
1643        } else if (da < 0) {
1644            removeInvisibleViewsAtEnd();
1645        }
1646        updated |= getChildCount() < childCount;
1647
1648        if (updated) {
1649            updateRowSecondarySizeRefresh();
1650        }
1651
1652        mBaseGridView.invalidate();
1653        return da;
1654    }
1655
1656    // scroll in second direction will not add/prune views
1657    private int scrollDirectionSecondary(int dy) {
1658        if (dy == 0) {
1659            return 0;
1660        }
1661        offsetChildrenSecondary(-dy);
1662        mScrollOffsetSecondary += dy;
1663        mBaseGridView.invalidate();
1664        return dy;
1665    }
1666
1667    private void updateScrollMax() {
1668        if (mLastVisiblePos < 0) {
1669            return;
1670        }
1671        final boolean lastAvailable = mLastVisiblePos == mState.getItemCount() - 1;
1672        final boolean maxUnknown = mWindowAlignment.mainAxis().isMaxUnknown();
1673        if (!lastAvailable && maxUnknown) {
1674            return;
1675        }
1676        int maxEdge = Integer.MIN_VALUE;
1677        int rowIndex = -1;
1678        for (int i = 0; i < mRows.length; i++) {
1679            if (mRows[i].high > maxEdge) {
1680                maxEdge = mRows[i].high;
1681                rowIndex = i;
1682            }
1683        }
1684        int maxScroll = Integer.MAX_VALUE;
1685        for (int i = mLastVisiblePos; i >= mFirstVisiblePos; i--) {
1686            StaggeredGrid.Location location = mGrid.getLocation(i);
1687            if (location != null && location.row == rowIndex) {
1688                int savedMaxEdge = mWindowAlignment.mainAxis().getMaxEdge();
1689                mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1690                maxScroll = getPrimarySystemScrollPosition(findViewByPosition(i));
1691                mWindowAlignment.mainAxis().setMaxEdge(savedMaxEdge);
1692                break;
1693            }
1694        }
1695        if (lastAvailable) {
1696            mWindowAlignment.mainAxis().setMaxEdge(maxEdge);
1697            mWindowAlignment.mainAxis().setMaxScroll(maxScroll);
1698            if (DEBUG) Log.v(getTag(), "updating scroll maxEdge to " + maxEdge +
1699                    " scrollMax to " + maxScroll);
1700        } else {
1701            // the maxScroll for currently last visible item is larger,
1702            // so we must invalidate the max scroll value.
1703            if (maxScroll > mWindowAlignment.mainAxis().getMaxScroll()) {
1704                mWindowAlignment.mainAxis().invalidateScrollMax();
1705                if (DEBUG) Log.v(getTag(), "Invalidate scrollMax since it should be "
1706                        + "greater than " + maxScroll);
1707            }
1708        }
1709    }
1710
1711    private void updateScrollMin() {
1712        if (mFirstVisiblePos < 0) {
1713            return;
1714        }
1715        final boolean firstAvailable = mFirstVisiblePos == 0;
1716        final boolean minUnknown = mWindowAlignment.mainAxis().isMinUnknown();
1717        if (!firstAvailable && minUnknown) {
1718            return;
1719        }
1720        int minEdge = Integer.MAX_VALUE;
1721        int rowIndex = -1;
1722        for (int i = 0; i < mRows.length; i++) {
1723            if (mRows[i].low < minEdge) {
1724                minEdge = mRows[i].low;
1725                rowIndex = i;
1726            }
1727        }
1728        int minScroll = Integer.MIN_VALUE;
1729        for (int i = mFirstVisiblePos; i <= mLastVisiblePos; i++) {
1730            StaggeredGrid.Location location = mGrid.getLocation(i);
1731            if (location != null && location.row == rowIndex) {
1732                int savedMinEdge = mWindowAlignment.mainAxis().getMinEdge();
1733                mWindowAlignment.mainAxis().setMinEdge(minEdge);
1734                minScroll = getPrimarySystemScrollPosition(findViewByPosition(i));
1735                mWindowAlignment.mainAxis().setMinEdge(savedMinEdge);
1736                break;
1737            }
1738        }
1739        if (firstAvailable) {
1740            mWindowAlignment.mainAxis().setMinEdge(minEdge);
1741            mWindowAlignment.mainAxis().setMinScroll(minScroll);
1742            if (DEBUG) Log.v(getTag(), "updating scroll minEdge to " + minEdge +
1743                    " scrollMin to " + minScroll);
1744        } else {
1745            // the minScroll for currently first visible item is smaller,
1746            // so we must invalidate the min scroll value.
1747            if (minScroll < mWindowAlignment.mainAxis().getMinScroll()) {
1748                mWindowAlignment.mainAxis().invalidateScrollMin();
1749                if (DEBUG) Log.v(getTag(), "Invalidate scrollMin, since it should be "
1750                        + "less than " + minScroll);
1751            }
1752        }
1753    }
1754
1755    private void updateScrollSecondAxis() {
1756        mWindowAlignment.secondAxis().setMinEdge(0);
1757        mWindowAlignment.secondAxis().setMaxEdge(getSizeSecondary());
1758    }
1759
1760    private void initScrollController() {
1761        // mScrollOffsetPrimary and mScrollOffsetSecondary includes the padding.
1762        // e.g. when topPadding is 16 for horizontal grid view,  the initial
1763        // mScrollOffsetSecondary is -16.  fastLayout() put views based on offsets(not padding),
1764        // when padding changes to 20,  we also need update mScrollOffsetSecondary to -20 before
1765        // fastLayout() is performed
1766        int paddingPrimaryDiff, paddingSecondaryDiff;
1767        if (mOrientation == HORIZONTAL) {
1768            paddingPrimaryDiff = getPaddingLeft() - mWindowAlignment.horizontal.getPaddingLow();
1769            paddingSecondaryDiff = getPaddingTop() - mWindowAlignment.vertical.getPaddingLow();
1770        } else {
1771            paddingPrimaryDiff = getPaddingTop() - mWindowAlignment.vertical.getPaddingLow();
1772            paddingSecondaryDiff = getPaddingLeft() - mWindowAlignment.horizontal.getPaddingLow();
1773        }
1774        mScrollOffsetPrimary -= paddingPrimaryDiff;
1775        mScrollOffsetSecondary -= paddingSecondaryDiff;
1776
1777        mWindowAlignment.horizontal.setSize(getWidth());
1778        mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight());
1779        mWindowAlignment.vertical.setSize(getHeight());
1780        mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom());
1781        mSizePrimary = mWindowAlignment.mainAxis().getSize();
1782
1783        if (DEBUG) {
1784            Log.v(getTag(), "initScrollController mSizePrimary " + mSizePrimary
1785                    + " mWindowAlignment " + mWindowAlignment);
1786        }
1787    }
1788
1789    public void setSelection(RecyclerView parent, int position) {
1790        setSelection(parent, position, false);
1791    }
1792
1793    public void setSelectionSmooth(RecyclerView parent, int position) {
1794        setSelection(parent, position, true);
1795    }
1796
1797    public int getSelection() {
1798        return mFocusPosition;
1799    }
1800
1801    public void setSelection(RecyclerView parent, int position, boolean smooth) {
1802        if (mFocusPosition == position) {
1803            return;
1804        }
1805        View view = findViewByPosition(position);
1806        if (view != null) {
1807            scrollToView(view, smooth);
1808        } else {
1809            mFocusPosition = position;
1810            mFocusPositionOffset = 0;
1811            if (!mLayoutEnabled) {
1812                return;
1813            }
1814            if (smooth) {
1815                if (!hasDoneFirstLayout()) {
1816                    Log.w(getTag(), "setSelectionSmooth should " +
1817                            "not be called before first layout pass");
1818                    return;
1819                }
1820                LinearSmoothScroller linearSmoothScroller =
1821                        new LinearSmoothScroller(parent.getContext()) {
1822                    @Override
1823                    public PointF computeScrollVectorForPosition(int targetPosition) {
1824                        if (getChildCount() == 0) {
1825                            return null;
1826                        }
1827                        final int firstChildPos = getPosition(getChildAt(0));
1828                        final int direction = targetPosition < firstChildPos ? -1 : 1;
1829                        if (mOrientation == HORIZONTAL) {
1830                            return new PointF(direction, 0);
1831                        } else {
1832                            return new PointF(0, direction);
1833                        }
1834                    }
1835                    @Override
1836                    protected void onTargetFound(View targetView,
1837                            RecyclerView.State state, Action action) {
1838                        if (hasFocus()) {
1839                            targetView.requestFocus();
1840                        }
1841                        dispatchChildSelected();
1842                        if (getScrollPosition(targetView, mTempDeltas)) {
1843                            int dx, dy;
1844                            if (mOrientation == HORIZONTAL) {
1845                                dx = mTempDeltas[0];
1846                                dy = mTempDeltas[1];
1847                            } else {
1848                                dx = mTempDeltas[1];
1849                                dy = mTempDeltas[0];
1850                            }
1851                            final int distance = (int) Math.sqrt(dx * dx + dy * dy);
1852                            final int time = calculateTimeForDeceleration(distance);
1853                            action.update(dx, dy, time, mDecelerateInterpolator);
1854                        }
1855                    }
1856                };
1857                linearSmoothScroller.setTargetPosition(position);
1858                startSmoothScroll(linearSmoothScroller);
1859            } else {
1860                mForceFullLayout = true;
1861                parent.requestLayout();
1862            }
1863        }
1864    }
1865
1866    @Override
1867    public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
1868        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
1869            int pos = mFocusPosition + mFocusPositionOffset;
1870            if (positionStart <= pos) {
1871                mFocusPositionOffset += itemCount;
1872            }
1873        }
1874    }
1875
1876    @Override
1877    public void onItemsChanged(RecyclerView recyclerView) {
1878        mFocusPositionOffset = 0;
1879    }
1880
1881    @Override
1882    public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) {
1883        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
1884            int pos = mFocusPosition + mFocusPositionOffset;
1885            if (positionStart <= pos) {
1886                if (positionStart + itemCount > pos) {
1887                    // stop updating offset after the focus item was removed
1888                    mFocusPositionOffset = Integer.MIN_VALUE;
1889                } else {
1890                    mFocusPositionOffset -= itemCount;
1891                }
1892            }
1893        }
1894    }
1895
1896    public void onItemsMoved(RecyclerView recyclerView, int fromPosition, int toPosition,
1897            int itemCount) {
1898        if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) {
1899            int pos = mFocusPosition + mFocusPositionOffset;
1900            if (fromPosition <= pos && pos < fromPosition + itemCount) {
1901                // moved items include focused position
1902                mFocusPositionOffset += toPosition - fromPosition;
1903            } else if (fromPosition < pos && toPosition > pos - itemCount) {
1904                // move items before focus position to after focused position
1905                mFocusPositionOffset -= itemCount;
1906            } else if (fromPosition > pos && toPosition < pos) {
1907                // move items after focus position to before focused position
1908                mFocusPositionOffset += itemCount;
1909            }
1910        }
1911    }
1912
1913    @Override
1914    public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) {
1915        if (mFocusSearchDisabled) {
1916            return true;
1917        }
1918        if (!mInLayout) {
1919            scrollToView(child, true);
1920        }
1921        return true;
1922    }
1923
1924    @Override
1925    public boolean requestChildRectangleOnScreen(RecyclerView parent, View view, Rect rect,
1926            boolean immediate) {
1927        if (DEBUG) Log.v(getTag(), "requestChildRectangleOnScreen " + view + " " + rect);
1928        return false;
1929    }
1930
1931    int getScrollOffsetX() {
1932        return mOrientation == HORIZONTAL ? mScrollOffsetPrimary : mScrollOffsetSecondary;
1933    }
1934
1935    int getScrollOffsetY() {
1936        return mOrientation == HORIZONTAL ? mScrollOffsetSecondary : mScrollOffsetPrimary;
1937    }
1938
1939    public void getViewSelectedOffsets(View view, int[] offsets) {
1940        if (mOrientation == HORIZONTAL) {
1941            offsets[0] = getPrimarySystemScrollPosition(view) - mScrollOffsetPrimary;
1942            offsets[1] = getSecondarySystemScrollPosition(view) - mScrollOffsetSecondary;
1943        } else {
1944            offsets[1] = getPrimarySystemScrollPosition(view) - mScrollOffsetPrimary;
1945            offsets[0] = getSecondarySystemScrollPosition(view) - mScrollOffsetSecondary;
1946        }
1947    }
1948
1949    private int getPrimarySystemScrollPosition(View view) {
1950        int viewCenterPrimary = mScrollOffsetPrimary + getViewCenter(view);
1951        int pos = getPositionByView(view);
1952        StaggeredGrid.Location location = mGrid.getLocation(pos);
1953        final int row = location.row;
1954        boolean isFirst = mFirstVisiblePos == 0;
1955        // TODO: change to use State object in onRequestChildFocus()
1956        boolean isLast = mLastVisiblePos == (mState == null ?
1957                getItemCount() : mState.getItemCount()) - 1;
1958        if (isFirst || isLast) {
1959            for (int i = getChildCount() - 1; i >= 0; i--) {
1960                int position = getPositionByIndex(i);
1961                StaggeredGrid.Location loc = mGrid.getLocation(position);
1962                if (loc != null && loc.row == row) {
1963                    if (position < pos) {
1964                        isFirst = false;
1965                    } else if (position > pos) {
1966                        isLast = false;
1967                    }
1968                }
1969            }
1970        }
1971        return mWindowAlignment.mainAxis().getSystemScrollPos(viewCenterPrimary, isFirst, isLast);
1972    }
1973
1974    private int getSecondarySystemScrollPosition(View view) {
1975        int viewCenterSecondary = mScrollOffsetSecondary + getViewCenterSecondary(view);
1976        int pos = getPositionByView(view);
1977        StaggeredGrid.Location location = mGrid.getLocation(pos);
1978        final int row = location.row;
1979        boolean isFirst = row == 0;
1980        boolean isLast = row == mGrid.getNumRows() - 1;
1981        return mWindowAlignment.secondAxis().getSystemScrollPos(viewCenterSecondary,
1982                isFirst, isLast);
1983    }
1984
1985    /**
1986     * Scroll to a given child view and change mFocusPosition.
1987     */
1988    private void scrollToView(View view, boolean smooth) {
1989        int newFocusPosition = getPositionByView(view);
1990        if (newFocusPosition != mFocusPosition) {
1991            mFocusPosition = newFocusPosition;
1992            mFocusPositionOffset = 0;
1993            if (!mInLayout) {
1994                dispatchChildSelected();
1995            }
1996        }
1997        if (mBaseGridView.isChildrenDrawingOrderEnabledInternal()) {
1998            mBaseGridView.invalidate();
1999        }
2000        if (view == null) {
2001            return;
2002        }
2003        if (!view.hasFocus() && mBaseGridView.hasFocus()) {
2004            // transfer focus to the child if it does not have focus yet (e.g. triggered
2005            // by setSelection())
2006            view.requestFocus();
2007        }
2008        if (!mScrollEnabled) {
2009            return;
2010        }
2011        if (getScrollPosition(view, mTempDeltas)) {
2012            scrollGrid(mTempDeltas[0], mTempDeltas[1], smooth);
2013        }
2014    }
2015
2016    private boolean getScrollPosition(View view, int[] deltas) {
2017        switch (mFocusScrollStrategy) {
2018        case BaseGridView.FOCUS_SCROLL_ALIGNED:
2019        default:
2020            return getAlignedPosition(view, deltas);
2021        case BaseGridView.FOCUS_SCROLL_ITEM:
2022        case BaseGridView.FOCUS_SCROLL_PAGE:
2023            return getNoneAlignedPosition(view, deltas);
2024        }
2025    }
2026
2027    private boolean getNoneAlignedPosition(View view, int[] deltas) {
2028        int pos = getPositionByView(view);
2029        int viewMin = getViewMin(view);
2030        int viewMax = getViewMax(view);
2031        // we either align "firstView" to left/top padding edge
2032        // or align "lastView" to right/bottom padding edge
2033        View firstView = null;
2034        View lastView = null;
2035        int paddingLow = mWindowAlignment.mainAxis().getPaddingLow();
2036        int clientSize = mWindowAlignment.mainAxis().getClientSize();
2037        final int row = mGrid.getLocation(pos).row;
2038        if (viewMin < paddingLow) {
2039            // view enters low padding area:
2040            firstView = view;
2041            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
2042                // scroll one "page" left/top,
2043                // align first visible item of the "page" at the low padding edge.
2044                while (!prependOneVisibleItem()) {
2045                    List<Integer> positions =
2046                            mGrid.getItemPositionsInRows(mFirstVisiblePos, pos)[row];
2047                    firstView = findViewByPosition(positions.get(0));
2048                    if (viewMax - getViewMin(firstView) > clientSize) {
2049                        if (positions.size() > 1) {
2050                            firstView = findViewByPosition(positions.get(1));
2051                        }
2052                        break;
2053                    }
2054                }
2055            }
2056        } else if (viewMax > clientSize + paddingLow) {
2057            // view enters high padding area:
2058            if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) {
2059                // scroll whole one page right/bottom, align view at the low padding edge.
2060                firstView = view;
2061                do {
2062                    List<Integer> positions =
2063                            mGrid.getItemPositionsInRows(pos, mLastVisiblePos)[row];
2064                    lastView = findViewByPosition(positions.get(positions.size() - 1));
2065                    if (getViewMax(lastView) - viewMin > clientSize) {
2066                        lastView = null;
2067                        break;
2068                    }
2069                } while (!appendOneVisibleItem());
2070                if (lastView != null) {
2071                    // however if we reached end,  we should align last view.
2072                    firstView = null;
2073                }
2074            } else {
2075                lastView = view;
2076            }
2077        }
2078        int scrollPrimary = 0;
2079        int scrollSecondary = 0;
2080        if (firstView != null) {
2081            scrollPrimary = getViewMin(firstView) - paddingLow;
2082        } else if (lastView != null) {
2083            scrollPrimary = getViewMax(lastView) - (paddingLow + clientSize);
2084        }
2085        View secondaryAlignedView;
2086        if (firstView != null) {
2087            secondaryAlignedView = firstView;
2088        } else if (lastView != null) {
2089            secondaryAlignedView = lastView;
2090        } else {
2091            secondaryAlignedView = view;
2092        }
2093        scrollSecondary = getSecondarySystemScrollPosition(secondaryAlignedView);
2094        scrollSecondary -= mScrollOffsetSecondary;
2095        if (scrollPrimary != 0 || scrollSecondary != 0) {
2096            deltas[0] = scrollPrimary;
2097            deltas[1] = scrollSecondary;
2098            return true;
2099        }
2100        return false;
2101    }
2102
2103    private boolean getAlignedPosition(View view, int[] deltas) {
2104        int scrollPrimary = getPrimarySystemScrollPosition(view);
2105        int scrollSecondary = getSecondarySystemScrollPosition(view);
2106        if (DEBUG) {
2107            Log.v(getTag(), "getAlignedPosition " + scrollPrimary + " " + scrollSecondary
2108                    +" " + mWindowAlignment);
2109        }
2110        scrollPrimary -= mScrollOffsetPrimary;
2111        scrollSecondary -= mScrollOffsetSecondary;
2112        if (scrollPrimary != 0 || scrollSecondary != 0) {
2113            deltas[0] = scrollPrimary;
2114            deltas[1] = scrollSecondary;
2115            return true;
2116        }
2117        return false;
2118    }
2119
2120    private void scrollGrid(int scrollPrimary, int scrollSecondary, boolean smooth) {
2121        if (mInLayout) {
2122            scrollDirectionPrimary(scrollPrimary);
2123            scrollDirectionSecondary(scrollSecondary);
2124        } else {
2125            int scrollX;
2126            int scrollY;
2127            if (mOrientation == HORIZONTAL) {
2128                scrollX = scrollPrimary;
2129                scrollY = scrollSecondary;
2130            } else {
2131                scrollX = scrollSecondary;
2132                scrollY = scrollPrimary;
2133            }
2134            if (smooth) {
2135                mBaseGridView.smoothScrollBy(scrollX, scrollY);
2136            } else {
2137                mBaseGridView.scrollBy(scrollX, scrollY);
2138            }
2139        }
2140    }
2141
2142    public void setPruneChild(boolean pruneChild) {
2143        if (mPruneChild != pruneChild) {
2144            mPruneChild = pruneChild;
2145            if (mPruneChild) {
2146                requestLayout();
2147            }
2148        }
2149    }
2150
2151    public boolean getPruneChild() {
2152        return mPruneChild;
2153    }
2154
2155    public void setScrollEnabled(boolean scrollEnabled) {
2156        if (mScrollEnabled != scrollEnabled) {
2157            mScrollEnabled = scrollEnabled;
2158            if (mScrollEnabled && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) {
2159                View focusView = findViewByPosition(mFocusPosition == NO_POSITION ? 0 :
2160                    mFocusPosition);
2161                if (focusView != null) {
2162                    scrollToView(focusView, true);
2163                }
2164            }
2165        }
2166    }
2167
2168    public boolean isScrollEnabled() {
2169        return mScrollEnabled;
2170    }
2171
2172    private int findImmediateChildIndex(View view) {
2173        while (view != null && view != mBaseGridView) {
2174            int index = mBaseGridView.indexOfChild(view);
2175            if (index >= 0) {
2176                return index;
2177            }
2178            view = (View) view.getParent();
2179        }
2180        return NO_POSITION;
2181    }
2182
2183    void setFocusSearchDisabled(boolean disabled) {
2184        mFocusSearchDisabled = disabled;
2185    }
2186
2187    boolean isFocusSearchDisabled() {
2188        return mFocusSearchDisabled;
2189    }
2190
2191    @Override
2192    public View onInterceptFocusSearch(View focused, int direction) {
2193        if (mFocusSearchDisabled) {
2194            return focused;
2195        }
2196        return null;
2197    }
2198
2199    boolean hasPreviousViewInSameRow(int pos) {
2200        if (mGrid == null || pos == NO_POSITION) {
2201            return false;
2202        }
2203        if (mFirstVisiblePos > 0) {
2204            return true;
2205        }
2206        final int focusedRow = mGrid.getLocation(pos).row;
2207        for (int i = getChildCount() - 1; i >= 0; i--) {
2208            int position = getPositionByIndex(i);
2209            StaggeredGrid.Location loc = mGrid.getLocation(position);
2210            if (loc != null && loc.row == focusedRow) {
2211                if (position < pos) {
2212                    return true;
2213                }
2214            }
2215        }
2216        return false;
2217    }
2218
2219    @Override
2220    public boolean onAddFocusables(RecyclerView recyclerView,
2221            ArrayList<View> views, int direction, int focusableMode) {
2222        if (mFocusSearchDisabled) {
2223            return true;
2224        }
2225        // If this viewgroup or one of its children currently has focus then we
2226        // consider our children for focus searching in main direction on the same row.
2227        // If this viewgroup has no focus and using focus align, we want the system
2228        // to ignore our children and pass focus to the viewgroup, which will pass
2229        // focus on to its children appropriately.
2230        // If this viewgroup has no focus and not using focus align, we want to
2231        // consider the child that does not overlap with padding area.
2232        if (recyclerView.hasFocus()) {
2233            final int movement = getMovement(direction);
2234            if (movement != PREV_ITEM && movement != NEXT_ITEM) {
2235                // Move on secondary direction uses default addFocusables().
2236                return false;
2237            }
2238            final View focused = recyclerView.findFocus();
2239            final int focusedPos = getPositionByIndex(findImmediateChildIndex(focused));
2240            // Add focusables of focused item.
2241            if (focusedPos != NO_POSITION) {
2242                findViewByPosition(focusedPos).addFocusables(views,  direction, focusableMode);
2243            }
2244            final int focusedRow = mGrid != null && focusedPos != NO_POSITION ?
2245                    mGrid.getLocation(focusedPos).row : NO_POSITION;
2246            // Add focusables of next neighbor of same row on the focus search direction.
2247            if (mGrid != null) {
2248                final int focusableCount = views.size();
2249                for (int i = 0, count = getChildCount(); i < count; i++) {
2250                    int index = movement == NEXT_ITEM ? i : count - 1 - i;
2251                    final View child = getChildAt(index);
2252                    if (child.getVisibility() != View.VISIBLE) {
2253                        continue;
2254                    }
2255                    int position = getPositionByIndex(index);
2256                    StaggeredGrid.Location loc = mGrid.getLocation(position);
2257                    if (focusedRow == NO_POSITION || (loc != null && loc.row == focusedRow)) {
2258                        if (focusedPos == NO_POSITION ||
2259                                (movement == NEXT_ITEM && position > focusedPos)
2260                                || (movement == PREV_ITEM && position < focusedPos)) {
2261                            child.addFocusables(views,  direction, focusableMode);
2262                            if (views.size() > focusableCount) {
2263                                break;
2264                            }
2265                        }
2266                    }
2267                }
2268            }
2269        } else {
2270            if (mFocusScrollStrategy != BaseGridView.FOCUS_SCROLL_ALIGNED) {
2271                // adding views not overlapping padding area to avoid scrolling in gaining focus
2272                int left = mWindowAlignment.mainAxis().getPaddingLow();
2273                int right = mWindowAlignment.mainAxis().getClientSize() + left;
2274                int focusableCount = views.size();
2275                for (int i = 0, count = getChildCount(); i < count; i++) {
2276                    View child = getChildAt(i);
2277                    if (child.getVisibility() == View.VISIBLE) {
2278                        if (getViewMin(child) >= left && getViewMax(child) <= right) {
2279                            child.addFocusables(views, direction, focusableMode);
2280                        }
2281                    }
2282                }
2283                // if we cannot find any, then just add all children.
2284                if (views.size() == focusableCount) {
2285                    for (int i = 0, count = getChildCount(); i < count; i++) {
2286                        View child = getChildAt(i);
2287                        if (child.getVisibility() == View.VISIBLE) {
2288                            child.addFocusables(views, direction, focusableMode);
2289                        }
2290                    }
2291                    if (views.size() != focusableCount) {
2292                        return true;
2293                    }
2294                } else {
2295                    return true;
2296                }
2297                // if still cannot find any, fall through and add itself
2298            }
2299            if (recyclerView.isFocusable()) {
2300                views.add(recyclerView);
2301            }
2302        }
2303        return true;
2304    }
2305
2306    @Override
2307    public View onFocusSearchFailed(View focused, int direction, Recycler recycler,
2308            RecyclerView.State state) {
2309        if (DEBUG) Log.v(getTag(), "onFocusSearchFailed direction " + direction);
2310
2311        View view = null;
2312        int movement = getMovement(direction);
2313        if (mNumRows == 1) {
2314            // for simple row, use LinearSmoothScroller to smooth animation.
2315            // It will stay at a fixed cap speed in continuous scroll.
2316            if (movement == NEXT_ITEM) {
2317                int newPos = mFocusPosition + mNumRows;
2318                if (newPos < getItemCount()) {
2319                    setSelectionSmooth(mBaseGridView, newPos);
2320                    view = focused;
2321                } else {
2322                    if (!mFocusOutEnd) {
2323                        view = focused;
2324                    }
2325                }
2326            } else if (movement == PREV_ITEM){
2327                int newPos = mFocusPosition - mNumRows;
2328                if (newPos >= 0) {
2329                    setSelectionSmooth(mBaseGridView, newPos);
2330                    view = focused;
2331                } else {
2332                    if (!mFocusOutFront) {
2333                        view = focused;
2334                    }
2335                }
2336            }
2337        } else if (mNumRows > 1) {
2338            // for possible staggered grid,  we need guarantee focus to same row/column.
2339            // TODO: we may also use LinearSmoothScroller.
2340            saveContext(recycler, state);
2341            final FocusFinder ff = FocusFinder.getInstance();
2342            if (movement == NEXT_ITEM) {
2343                while (view == null && !appendOneVisibleItem()) {
2344                    view = ff.findNextFocus(mBaseGridView, focused, direction);
2345                }
2346            } else if (movement == PREV_ITEM){
2347                while (view == null && !prependOneVisibleItem()) {
2348                    view = ff.findNextFocus(mBaseGridView, focused, direction);
2349                }
2350            }
2351            if (view == null) {
2352                // returning the same view to prevent focus lost when scrolling past the end of the list
2353                if (movement == PREV_ITEM) {
2354                    view = mFocusOutFront ? null : focused;
2355                } else if (movement == NEXT_ITEM){
2356                    view = mFocusOutEnd ? null : focused;
2357                }
2358            }
2359            leaveContext();
2360        }
2361        if (DEBUG) Log.v(getTag(), "returning view " + view);
2362        return view;
2363    }
2364
2365    boolean gridOnRequestFocusInDescendants(RecyclerView recyclerView, int direction,
2366            Rect previouslyFocusedRect) {
2367        switch (mFocusScrollStrategy) {
2368        case BaseGridView.FOCUS_SCROLL_ALIGNED:
2369        default:
2370            return gridOnRequestFocusInDescendantsAligned(recyclerView,
2371                    direction, previouslyFocusedRect);
2372        case BaseGridView.FOCUS_SCROLL_PAGE:
2373        case BaseGridView.FOCUS_SCROLL_ITEM:
2374            return gridOnRequestFocusInDescendantsUnaligned(recyclerView,
2375                    direction, previouslyFocusedRect);
2376        }
2377    }
2378
2379    private boolean gridOnRequestFocusInDescendantsAligned(RecyclerView recyclerView,
2380            int direction, Rect previouslyFocusedRect) {
2381        View view = findViewByPosition(mFocusPosition);
2382        if (view != null) {
2383            boolean result = view.requestFocus(direction, previouslyFocusedRect);
2384            if (!result && DEBUG) {
2385                Log.w(getTag(), "failed to request focus on " + view);
2386            }
2387            return result;
2388        }
2389        return false;
2390    }
2391
2392    private boolean gridOnRequestFocusInDescendantsUnaligned(RecyclerView recyclerView,
2393            int direction, Rect previouslyFocusedRect) {
2394        // focus to view not overlapping padding area to avoid scrolling in gaining focus
2395        int index;
2396        int increment;
2397        int end;
2398        int count = getChildCount();
2399        if ((direction & View.FOCUS_FORWARD) != 0) {
2400            index = 0;
2401            increment = 1;
2402            end = count;
2403        } else {
2404            index = count - 1;
2405            increment = -1;
2406            end = -1;
2407        }
2408        int left = mWindowAlignment.mainAxis().getPaddingLow();
2409        int right = mWindowAlignment.mainAxis().getClientSize() + left;
2410        for (int i = index; i != end; i += increment) {
2411            View child = getChildAt(i);
2412            if (child.getVisibility() == View.VISIBLE) {
2413                if (getViewMin(child) >= left && getViewMax(child) <= right) {
2414                    if (child.requestFocus(direction, previouslyFocusedRect)) {
2415                        return true;
2416                    }
2417                }
2418            }
2419        }
2420        return false;
2421    }
2422
2423    private final static int PREV_ITEM = 0;
2424    private final static int NEXT_ITEM = 1;
2425    private final static int PREV_ROW = 2;
2426    private final static int NEXT_ROW = 3;
2427
2428    private int getMovement(int direction) {
2429        int movement = View.FOCUS_LEFT;
2430
2431        if (mOrientation == HORIZONTAL) {
2432            switch(direction) {
2433                case View.FOCUS_LEFT:
2434                    movement = PREV_ITEM;
2435                    break;
2436                case View.FOCUS_RIGHT:
2437                    movement = NEXT_ITEM;
2438                    break;
2439                case View.FOCUS_UP:
2440                    movement = PREV_ROW;
2441                    break;
2442                case View.FOCUS_DOWN:
2443                    movement = NEXT_ROW;
2444                    break;
2445            }
2446         } else if (mOrientation == VERTICAL) {
2447             switch(direction) {
2448                 case View.FOCUS_LEFT:
2449                     movement = PREV_ROW;
2450                     break;
2451                 case View.FOCUS_RIGHT:
2452                     movement = NEXT_ROW;
2453                     break;
2454                 case View.FOCUS_UP:
2455                     movement = PREV_ITEM;
2456                     break;
2457                 case View.FOCUS_DOWN:
2458                     movement = NEXT_ITEM;
2459                     break;
2460             }
2461         }
2462
2463        return movement;
2464    }
2465
2466    int getChildDrawingOrder(RecyclerView recyclerView, int childCount, int i) {
2467        View view = findViewByPosition(mFocusPosition);
2468        if (view == null) {
2469            return i;
2470        }
2471        int focusIndex = recyclerView.indexOfChild(view);
2472        // supposely 0 1 2 3 4 5 6 7 8 9, 4 is the center item
2473        // drawing order is 0 1 2 3 9 8 7 6 5 4
2474        if (i < focusIndex) {
2475            return i;
2476        } else if (i < childCount - 1) {
2477            return focusIndex + childCount - 1 - i;
2478        } else {
2479            return focusIndex;
2480        }
2481    }
2482
2483    @Override
2484    public void onAdapterChanged(RecyclerView.Adapter oldAdapter,
2485            RecyclerView.Adapter newAdapter) {
2486        discardLayoutInfo();
2487        mFocusPosition = NO_POSITION;
2488        mFocusPositionOffset = 0;
2489        super.onAdapterChanged(oldAdapter, newAdapter);
2490    }
2491
2492    private void discardLayoutInfo() {
2493        mGrid = null;
2494        mRows = null;
2495        mRowSizeSecondary = null;
2496        mFirstVisiblePos = -1;
2497        mLastVisiblePos = -1;
2498        mRowSecondarySizeRefresh = false;
2499    }
2500
2501    public void setLayoutEnabled(boolean layoutEnabled) {
2502        if (mLayoutEnabled != layoutEnabled) {
2503            mLayoutEnabled = layoutEnabled;
2504            requestLayout();
2505        }
2506    }
2507}
2508