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