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