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