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