GridLayoutManager.java revision 5b1f117209e8a38d6d6b004c3c0d0285acc9b27f
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.animation.TimeAnimator; 17import android.content.Context; 18import android.graphics.Rect; 19import android.support.v7.widget.RecyclerView; 20import android.support.v7.widget.RecyclerView.Adapter; 21import android.support.v7.widget.RecyclerView.Recycler; 22 23import static android.support.v7.widget.RecyclerView.NO_ID; 24import static android.support.v7.widget.RecyclerView.NO_POSITION; 25import static android.support.v7.widget.RecyclerView.HORIZONTAL; 26import static android.support.v7.widget.RecyclerView.VERTICAL; 27 28import android.util.AttributeSet; 29import android.util.Log; 30import android.view.FocusFinder; 31import android.view.Gravity; 32import android.view.View; 33import android.view.ViewParent; 34import android.view.View.MeasureSpec; 35import android.view.ViewGroup.MarginLayoutParams; 36import android.view.ViewGroup; 37import android.view.animation.DecelerateInterpolator; 38import android.view.animation.Interpolator; 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 three internal jobs: 50 * - Saves optical bounds insets. 51 * - Caches focus align view center. 52 * - Manages child view layout animation. 53 */ 54 static class LayoutParams extends RecyclerView.LayoutParams { 55 56 // The view is saved only during animation. 57 private View mView; 58 59 // For placement 60 private int mLeftInset; 61 private int mTopInset; 62 private int mRighInset; 63 private int mBottomInset; 64 65 // For alignment 66 private int mAlignX; 67 private int mAlignY; 68 69 // For animations 70 private TimeAnimator mAnimator; 71 private long mDuration; 72 private boolean mFirstAttached; 73 // current virtual view position (scrollOffset + left/top) in the GridLayoutManager 74 private int mViewX, mViewY; 75 // animation start value of translation x and y 76 private float mAnimationStartTranslationX, mAnimationStartTranslationY; 77 78 public LayoutParams(Context c, AttributeSet attrs) { 79 super(c, attrs); 80 } 81 82 public LayoutParams(int width, int height) { 83 super(width, height); 84 } 85 86 public LayoutParams(MarginLayoutParams source) { 87 super(source); 88 } 89 90 public LayoutParams(ViewGroup.LayoutParams source) { 91 super(source); 92 } 93 94 public LayoutParams(RecyclerView.LayoutParams source) { 95 super(source); 96 } 97 98 public LayoutParams(LayoutParams source) { 99 super(source); 100 } 101 102 void onViewAttached() { 103 endAnimate(); 104 mFirstAttached = true; 105 } 106 107 void onViewDetached() { 108 endAnimate(); 109 } 110 111 int getAlignX() { 112 return mAlignX; 113 } 114 115 int getAlignY() { 116 return mAlignY; 117 } 118 119 int getOpticalLeft(View view) { 120 return view.getLeft() + mLeftInset; 121 } 122 123 int getOpticalTop(View view) { 124 return view.getTop() + mTopInset; 125 } 126 127 int getOpticalRight(View view) { 128 return view.getRight() - mRighInset; 129 } 130 131 int getOpticalBottom(View view) { 132 return view.getBottom() - mBottomInset; 133 } 134 135 int getOpticalWidth(View view) { 136 return view.getWidth() - mLeftInset - mRighInset; 137 } 138 139 int getOpticalHeight(View view) { 140 return view.getHeight() - mTopInset - 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 TimeAnimator.TimeListener mTimeListener = new TimeAnimator.TimeListener() { 159 @Override 160 public void onTimeUpdate(TimeAnimator animation, long totalTime, long deltaTime) { 161 if (mView == null) { 162 return; 163 } 164 if (totalTime >= mDuration) { 165 endAnimate(); 166 } else { 167 float fraction = (float) (totalTime / (double)mDuration); 168 float fractionToEnd = 1 - mAnimator 169 .getInterpolator().getInterpolation(fraction); 170 mView.setTranslationX(fractionToEnd * mAnimationStartTranslationX); 171 mView.setTranslationY(fractionToEnd * mAnimationStartTranslationY); 172 invalidateItemDecoration(); 173 } 174 } 175 }; 176 177 void startAnimate(GridLayoutManager layout, View view, long startDelay) { 178 if (mAnimator == null) { 179 mAnimator = new TimeAnimator(); 180 mAnimator.setTimeListener(mTimeListener); 181 } 182 if (mFirstAttached) { 183 // first time record the initial location and return without animation 184 // TODO do we need initial animation? 185 mViewX = layout.getScrollOffsetX() + getOpticalLeft(view); 186 mViewY = layout.getScrollOffsetY() + getOpticalTop(view); 187 mFirstAttached = false; 188 return; 189 } 190 if (!layout.isChildLayoutAnimated()) { 191 return; 192 } 193 mView = view; 194 int newViewX = layout.getScrollOffsetX() + getOpticalLeft(mView); 195 int newViewY = layout.getScrollOffsetY() + getOpticalTop(mView); 196 if (newViewX != mViewX || newViewY != mViewY) { 197 mAnimator.cancel(); 198 mAnimationStartTranslationX = mView.getTranslationX(); 199 mAnimationStartTranslationY = mView.getTranslationY(); 200 mAnimationStartTranslationX += mViewX - newViewX; 201 mAnimationStartTranslationY += mViewY - newViewY; 202 mDuration = layout.getChildLayoutAnimationDuration(); 203 mAnimator.setDuration(mDuration); 204 mAnimator.setInterpolator(layout.getChildLayoutAnimationInterpolator()); 205 mAnimator.setStartDelay(startDelay); 206 mAnimator.start(); 207 mViewX = newViewX; 208 mViewY = newViewY; 209 } 210 } 211 212 void endAnimate() { 213 if (mAnimator != null) { 214 mAnimator.end(); 215 } 216 if (mView != null) { 217 mView.setTranslationX(0); 218 mView.setTranslationY(0); 219 mView = null; 220 } 221 } 222 223 private void invalidateItemDecoration() { 224 ViewParent parent = mView.getParent(); 225 if (parent instanceof RecyclerView) { 226 // TODO: we only need invalidate parent if it has ItemDecoration 227 ((RecyclerView) parent).invalidate(); 228 } 229 } 230 } 231 232 private static final String TAG = "GridLayoutManager"; 233 private static final boolean DEBUG = false; 234 235 private static final Interpolator sDefaultAnimationChildLayoutInterpolator 236 = new DecelerateInterpolator(); 237 238 private static final long DEFAULT_CHILD_ANIMATION_DURATION_MS = 250; 239 240 private String getTag() { 241 return TAG + ":" + mBaseGridView.getId(); 242 } 243 244 private final BaseGridView mBaseGridView; 245 246 /** 247 * The orientation of a "row". 248 */ 249 private int mOrientation = HORIZONTAL; 250 251 private RecyclerView.Adapter mAdapter; 252 private RecyclerView.Recycler mRecycler; 253 254 private boolean mInLayout = false; 255 256 private OnChildSelectedListener mChildSelectedListener = null; 257 258 /** 259 * The focused position, it's not the currently visually aligned position 260 * but it is the final position that we intend to focus on. If there are 261 * multiple setSelection() called, mFocusPosition saves last value. 262 */ 263 private int mFocusPosition = NO_POSITION; 264 265 /** 266 * Force a full layout under certain situations. 267 */ 268 private boolean mForceFullLayout; 269 270 /** 271 * The scroll offsets of the viewport relative to the entire view. 272 */ 273 private int mScrollOffsetPrimary; 274 private int mScrollOffsetSecondary; 275 276 /** 277 * User-specified fixed size of each grid item in the secondary direction, can be 278 * 0 to be determined by parent size and number of rows. 279 */ 280 private int mItemLengthSecondaryRequested; 281 /** 282 * The fixed size of each grid item in the secondary direction. This corresponds to 283 * the row height, equal for all rows. Grid items may have variable length 284 * in the primary direction. 285 * 286 */ 287 private int mItemLengthSecondary; 288 289 /** 290 * Margin between items. 291 */ 292 private int mHorizontalMargin; 293 /** 294 * Margin between items vertically. 295 */ 296 private int mVerticalMargin; 297 /** 298 * Margin in main direction. 299 */ 300 private int mMarginPrimary; 301 /** 302 * Margin in second direction. 303 */ 304 private int mMarginSecondary; 305 /** 306 * How to position child in secondary direction. 307 */ 308 private int mGravity = Gravity.LEFT | Gravity.TOP; 309 /** 310 * The number of rows in the grid. 311 */ 312 private int mNumRows; 313 /** 314 * Number of rows requested, can be 0 to be determined by parent size and 315 * rowHeight. 316 */ 317 private int mNumRowsRequested = 1; 318 319 /** 320 * Tracking start/end position of each row for visible items. 321 */ 322 private StaggeredGrid.Row[] mRows; 323 324 /** 325 * Saves grid information of each view. 326 */ 327 private StaggeredGrid mGrid; 328 /** 329 * Position of first item (included) that has attached views. 330 */ 331 private int mFirstVisiblePos; 332 /** 333 * Position of last item (included) that has attached views. 334 */ 335 private int mLastVisiblePos; 336 337 /** 338 * Focus Scroll strategy. 339 */ 340 private int mFocusScrollStrategy = BaseGridView.FOCUS_SCROLL_ALIGNED; 341 /** 342 * Defines how item view is aligned in the window. 343 */ 344 private final WindowAlignment mWindowAlignment = new WindowAlignment(); 345 346 /** 347 * Defines how item view is aligned. 348 */ 349 private final ItemAlignment mItemAlignment = new ItemAlignment(); 350 351 /** 352 * Dimensions of the view, width or height depending on orientation. 353 */ 354 private int mSizePrimary; 355 356 /** 357 * Allow DPAD key to navigate out at the front of the View (where position = 0), 358 * default is false. 359 */ 360 private boolean mFocusOutFront; 361 362 /** 363 * Allow DPAD key to navigate out at the end of the view, default is false. 364 */ 365 private boolean mFocusOutEnd; 366 367 /** 368 * Animate layout changes from a child resizing or adding/removing a child. 369 */ 370 private boolean mAnimateChildLayout = true; 371 372 /** 373 * Interpolator used to animate layout of children. 374 */ 375 private Interpolator mAnimateLayoutChildInterpolator = sDefaultAnimationChildLayoutInterpolator; 376 377 /** 378 * Duration used to animate layout of children. 379 */ 380 private long mAnimateLayoutChildDuration = DEFAULT_CHILD_ANIMATION_DURATION_MS; 381 382 public GridLayoutManager(BaseGridView baseGridView) { 383 mBaseGridView = baseGridView; 384 } 385 386 public void setOrientation(int orientation) { 387 if (orientation != HORIZONTAL && orientation != VERTICAL) { 388 if (DEBUG) Log.v(getTag(), "invalid orientation: " + orientation); 389 return; 390 } 391 392 mOrientation = orientation; 393 mWindowAlignment.setOrientation(orientation); 394 mItemAlignment.setOrientation(orientation); 395 mForceFullLayout = true; 396 } 397 398 public int getFocusScrollStrategy() { 399 return mFocusScrollStrategy; 400 } 401 402 public void setFocusScrollStrategy(int focusScrollStrategy) { 403 mFocusScrollStrategy = focusScrollStrategy; 404 } 405 406 public void setWindowAlignment(int windowAlignment) { 407 mWindowAlignment.mainAxis().setWindowAlignment(windowAlignment); 408 } 409 410 public int getWindowAlignment() { 411 return mWindowAlignment.mainAxis().getWindowAlignment(); 412 } 413 414 public void setWindowAlignmentOffset(int alignmentOffset) { 415 mWindowAlignment.mainAxis().setWindowAlignmentOffset(alignmentOffset); 416 } 417 418 public int getWindowAlignmentOffset() { 419 return mWindowAlignment.mainAxis().getWindowAlignmentOffset(); 420 } 421 422 public void setWindowAlignmentOffsetPercent(float offsetPercent) { 423 mWindowAlignment.mainAxis().setWindowAlignmentOffsetPercent(offsetPercent); 424 } 425 426 public float getWindowAlignmentOffsetPercent() { 427 return mWindowAlignment.mainAxis().getWindowAlignmentOffsetPercent(); 428 } 429 430 public void setItemAlignmentOffset(int alignmentOffset) { 431 mItemAlignment.mainAxis().setItemAlignmentOffset(alignmentOffset); 432 updateChildAlignments(); 433 } 434 435 public int getItemAlignmentOffset() { 436 return mItemAlignment.mainAxis().getItemAlignmentOffset(); 437 } 438 439 public void setItemAlignmentOffsetPercent(float offsetPercent) { 440 mItemAlignment.mainAxis().setItemAlignmentOffsetPercent(offsetPercent); 441 updateChildAlignments(); 442 } 443 444 public float getItemAlignmentOffsetPercent() { 445 return mItemAlignment.mainAxis().getItemAlignmentOffsetPercent(); 446 } 447 448 public void setItemAlignmentViewId(int viewId) { 449 mItemAlignment.mainAxis().setItemAlignmentViewId(viewId); 450 updateChildAlignments(); 451 } 452 453 public int getItemAlignmentViewId() { 454 return mItemAlignment.mainAxis().getItemAlignmentViewId(); 455 } 456 457 public void setFocusOutAllowed(boolean throughFront, boolean throughEnd) { 458 mFocusOutFront = throughFront; 459 mFocusOutEnd = throughEnd; 460 } 461 462 public void setNumRows(int numRows) { 463 if (numRows < 0) throw new IllegalArgumentException(); 464 mNumRowsRequested = numRows; 465 mForceFullLayout = true; 466 } 467 468 public void setRowHeight(int height) { 469 if (height < 0) throw new IllegalArgumentException(); 470 mItemLengthSecondaryRequested = height; 471 } 472 473 public void setItemMargin(int margin) { 474 mVerticalMargin = mHorizontalMargin = margin; 475 mMarginPrimary = mMarginSecondary = margin; 476 } 477 478 public void setVerticalMargin(int margin) { 479 if (mOrientation == HORIZONTAL) { 480 mMarginSecondary = mVerticalMargin = margin; 481 } else { 482 mMarginPrimary = mVerticalMargin = margin; 483 } 484 } 485 486 public void setHorizontalMargin(int margin) { 487 if (mOrientation == HORIZONTAL) { 488 mMarginPrimary = mHorizontalMargin = margin; 489 } else { 490 mMarginSecondary = mHorizontalMargin = margin; 491 } 492 } 493 494 public int getVerticalMargin() { 495 return mVerticalMargin; 496 } 497 498 public int getHorizontalMargin() { 499 return mHorizontalMargin; 500 } 501 502 public void setGravity(int gravity) { 503 mGravity = gravity; 504 } 505 506 protected boolean hasDoneFirstLayout() { 507 return mGrid != null; 508 } 509 510 public void setOnChildSelectedListener(OnChildSelectedListener listener) { 511 mChildSelectedListener = listener; 512 } 513 514 private int getPositionByView(View view) { 515 return getPositionByIndex(mBaseGridView.indexOfChild(view)); 516 } 517 518 private int getPositionByIndex(int index) { 519 if (index < 0) { 520 return NO_POSITION; 521 } 522 return mFirstVisiblePos + index; 523 } 524 525 private View getViewByPosition(int position) { 526 int index = getIndexByPosition(position); 527 if (index < 0) { 528 return null; 529 } 530 return getChildAt(index); 531 } 532 533 private int getIndexByPosition(int position) { 534 if (mFirstVisiblePos < 0 || 535 position < mFirstVisiblePos || position > mLastVisiblePos) { 536 return NO_POSITION; 537 } 538 return position - mFirstVisiblePos; 539 } 540 541 private void dispatchChildSelected() { 542 if (mChildSelectedListener == null) { 543 return; 544 } 545 546 View view = getViewByPosition(mFocusPosition); 547 548 if (mFocusPosition != NO_POSITION) { 549 mChildSelectedListener.onChildSelected(mBaseGridView, view, mFocusPosition, 550 mAdapter.getItemId(mFocusPosition)); 551 } else { 552 mChildSelectedListener.onChildSelected(mBaseGridView, null, NO_POSITION, NO_ID); 553 } 554 } 555 556 @Override 557 public boolean canScrollHorizontally() { 558 // We can scroll horizontally if we have horizontal orientation, or if 559 // we are vertical and have more than one column. 560 return mOrientation == HORIZONTAL || mNumRows > 1; 561 } 562 563 @Override 564 public boolean canScrollVertically() { 565 // We can scroll vertically if we have vertical orientation, or if we 566 // are horizontal and have more than one row. 567 return mOrientation == VERTICAL || mNumRows > 1; 568 } 569 570 @Override 571 public RecyclerView.LayoutParams generateDefaultLayoutParams() { 572 return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 573 ViewGroup.LayoutParams.WRAP_CONTENT); 574 } 575 576 @Override 577 public RecyclerView.LayoutParams generateLayoutParams(Context context, AttributeSet attrs) { 578 return new LayoutParams(context, attrs); 579 } 580 581 @Override 582 public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { 583 if (lp instanceof LayoutParams) { 584 return new LayoutParams((LayoutParams) lp); 585 } else if (lp instanceof RecyclerView.LayoutParams) { 586 return new LayoutParams((RecyclerView.LayoutParams) lp); 587 } else if (lp instanceof MarginLayoutParams) { 588 return new LayoutParams((MarginLayoutParams) lp); 589 } else { 590 return new LayoutParams(lp); 591 } 592 } 593 594 protected View getViewForPosition(int position) { 595 View v = mRecycler.getViewForPosition(mAdapter, position); 596 if (v != null) { 597 ((LayoutParams) v.getLayoutParams()).onViewAttached(); 598 } 599 return v; 600 } 601 602 private int getViewMin(View v) { 603 LayoutParams p = (LayoutParams) v.getLayoutParams(); 604 return (mOrientation == HORIZONTAL) ? p.getOpticalLeft(v) : p.getOpticalTop(v); 605 } 606 607 private int getViewMax(View v) { 608 LayoutParams p = (LayoutParams) v.getLayoutParams(); 609 return (mOrientation == HORIZONTAL) ? p.getOpticalRight(v) : p.getOpticalBottom(v); 610 } 611 612 private int getViewCenter(View view) { 613 return (mOrientation == HORIZONTAL) ? getViewCenterX(view) : getViewCenterY(view); 614 } 615 616 private int getViewCenterSecondary(View view) { 617 return (mOrientation == HORIZONTAL) ? getViewCenterY(view) : getViewCenterX(view); 618 } 619 620 private int getViewCenterX(View v) { 621 LayoutParams p = (LayoutParams) v.getLayoutParams(); 622 return p.getOpticalLeft(v) + p.getAlignX(); 623 } 624 625 private int getViewCenterY(View v) { 626 LayoutParams p = (LayoutParams) v.getLayoutParams(); 627 return p.getOpticalTop(v) + p.getAlignY(); 628 } 629 630 /** 631 * Re-initialize data structures for a data change or handling invisible 632 * selection. The method tries its best to preserve position information so 633 * that staggered grid looks same before and after re-initialize. 634 * @param focusPosition The initial focusPosition that we would like to 635 * focus on. 636 * @return Actual position that can be focused on. 637 */ 638 private int init(RecyclerView.Adapter adapter, RecyclerView.Recycler recycler, 639 int focusPosition) { 640 641 final int newItemCount = adapter.getItemCount(); 642 643 if (focusPosition == NO_POSITION && newItemCount > 0) { 644 // if focus position is never set before, initialize it to 0 645 focusPosition = 0; 646 } 647 // If adapter has changed then caches are invalid; otherwise, 648 // we try to maintain each row's position if number of rows keeps the same 649 // and existing mGrid contains the focusPosition. 650 if (mRows != null && mNumRows == mRows.length && 651 mGrid != null && mGrid.getSize() > 0 && focusPosition >= 0 && 652 focusPosition >= mGrid.getFirstIndex() && 653 focusPosition <= mGrid.getLastIndex()) { 654 // strip mGrid to a subset (like a column) that contains focusPosition 655 mGrid.stripDownTo(focusPosition); 656 // make sure that remaining items do not exceed new adapter size 657 int firstIndex = mGrid.getFirstIndex(); 658 int lastIndex = mGrid.getLastIndex(); 659 if (DEBUG) { 660 Log .v(getTag(), "mGrid firstIndex " + firstIndex + " lastIndex " + lastIndex); 661 } 662 for (int i = lastIndex; i >=firstIndex; i--) { 663 if (i >= newItemCount) { 664 mGrid.removeLast(); 665 } 666 } 667 if (mGrid.getSize() == 0) { 668 focusPosition = newItemCount - 1; 669 // initialize row start locations 670 for (int i = 0; i < mNumRows; i++) { 671 mRows[i].low = 0; 672 mRows[i].high = 0; 673 } 674 if (DEBUG) Log.v(getTag(), "mGrid zero size"); 675 } else { 676 // initialize row start locations 677 for (int i = 0; i < mNumRows; i++) { 678 mRows[i].low = Integer.MAX_VALUE; 679 mRows[i].high = Integer.MIN_VALUE; 680 } 681 firstIndex = mGrid.getFirstIndex(); 682 lastIndex = mGrid.getLastIndex(); 683 if (focusPosition > lastIndex) { 684 focusPosition = mGrid.getLastIndex(); 685 } 686 if (DEBUG) { 687 Log.v(getTag(), "mGrid firstIndex " + firstIndex + " lastIndex " 688 + lastIndex + " focusPosition " + focusPosition); 689 } 690 // fill rows with minimal view positions of the subset 691 for (int i = firstIndex; i <= lastIndex; i++) { 692 View v = getViewByPosition(i); 693 if (v == null) { 694 continue; 695 } 696 int row = mGrid.getLocation(i).row; 697 int low = getViewMin(v) + mScrollOffsetPrimary; 698 if (low < mRows[row].low) { 699 mRows[row].low = mRows[row].high = low; 700 } 701 } 702 // fill other rows that does not include the subset using first item 703 int firstItemRowPosition = mRows[mGrid.getLocation(firstIndex).row].low; 704 if (firstItemRowPosition == Integer.MAX_VALUE) { 705 firstItemRowPosition = 0; 706 } 707 for (int i = 0; i < mNumRows; i++) { 708 if (mRows[i].low == Integer.MAX_VALUE) { 709 mRows[i].low = mRows[i].high = firstItemRowPosition; 710 } 711 } 712 } 713 714 // Same adapter, we can reuse any attached views 715 detachAndScrapAttachedViews(recycler); 716 717 } else { 718 // otherwise recreate data structure 719 mRows = new StaggeredGrid.Row[mNumRows]; 720 for (int i = 0; i < mNumRows; i++) { 721 mRows[i] = new StaggeredGrid.Row(); 722 } 723 mGrid = new StaggeredGridDefault(); 724 if (newItemCount == 0) { 725 focusPosition = NO_POSITION; 726 } else if (focusPosition >= newItemCount) { 727 focusPosition = newItemCount - 1; 728 } 729 730 // Adapter may have changed so remove all attached views permanently 731 removeAllViews(); 732 733 mScrollOffsetPrimary = 0; 734 mScrollOffsetSecondary = 0; 735 mWindowAlignment.reset(); 736 } 737 738 mAdapter = adapter; 739 mRecycler = recycler; 740 mGrid.setProvider(mGridProvider); 741 // mGrid share the same Row array information 742 mGrid.setRows(mRows); 743 mFirstVisiblePos = mLastVisiblePos = NO_POSITION; 744 745 initScrollController(); 746 747 return focusPosition; 748 } 749 750 // TODO: use recyclerview support for measuring the whole container, once 751 // it's available. 752 void gridOnMeasure(int widthSpec, int heightSpec, int[] result) { 753 int sizePrimary, sizeSecondary, modeSecondary, paddingSecondary; 754 int measuredSizeSecondary; 755 if (mOrientation == HORIZONTAL) { 756 sizePrimary = MeasureSpec.getSize(widthSpec); 757 sizeSecondary = MeasureSpec.getSize(heightSpec); 758 modeSecondary = MeasureSpec.getMode(heightSpec); 759 paddingSecondary = getPaddingTop() + getPaddingBottom(); 760 } else { 761 sizeSecondary = MeasureSpec.getSize(widthSpec); 762 sizePrimary = MeasureSpec.getSize(heightSpec); 763 modeSecondary = MeasureSpec.getMode(widthSpec); 764 paddingSecondary = getPaddingLeft() + getPaddingRight(); 765 } 766 switch (modeSecondary) { 767 case MeasureSpec.UNSPECIFIED: 768 if (mItemLengthSecondaryRequested == 0) { 769 if (mOrientation == HORIZONTAL) { 770 throw new IllegalStateException("Must specify rowHeight or view height"); 771 } else { 772 throw new IllegalStateException("Must specify columnWidth or view width"); 773 } 774 } 775 mItemLengthSecondary = mItemLengthSecondaryRequested; 776 if (mNumRowsRequested == 0) { 777 mNumRows = 1; 778 } else { 779 mNumRows = mNumRowsRequested; 780 } 781 measuredSizeSecondary = mItemLengthSecondary * mNumRows + mMarginSecondary 782 * (mNumRows - 1) + paddingSecondary; 783 break; 784 case MeasureSpec.AT_MOST: 785 case MeasureSpec.EXACTLY: 786 if (mNumRowsRequested == 0 && mItemLengthSecondaryRequested == 0) { 787 mNumRows = 1; 788 mItemLengthSecondary = sizeSecondary - paddingSecondary; 789 } else if (mNumRowsRequested == 0) { 790 mItemLengthSecondary = mItemLengthSecondaryRequested; 791 mNumRows = (sizeSecondary + mMarginSecondary) 792 / (mItemLengthSecondaryRequested + mMarginSecondary); 793 } else if (mItemLengthSecondaryRequested == 0) { 794 mNumRows = mNumRowsRequested; 795 mItemLengthSecondary = (sizeSecondary - paddingSecondary - mMarginSecondary 796 * (mNumRows - 1)) / mNumRows; 797 } else { 798 mNumRows = mNumRowsRequested; 799 mItemLengthSecondary = mItemLengthSecondaryRequested; 800 } 801 measuredSizeSecondary = sizeSecondary; 802 if (modeSecondary == MeasureSpec.AT_MOST) { 803 int childrenSize = mItemLengthSecondary * mNumRows + mMarginSecondary 804 * (mNumRows - 1) + paddingSecondary; 805 if (childrenSize < measuredSizeSecondary) { 806 measuredSizeSecondary = childrenSize; 807 } 808 } 809 break; 810 default: 811 throw new IllegalStateException("wrong spec"); 812 } 813 if (mOrientation == HORIZONTAL) { 814 result[0] = sizePrimary; 815 result[1] = measuredSizeSecondary; 816 } else { 817 result[0] = measuredSizeSecondary; 818 result[1] = sizePrimary; 819 } 820 if (DEBUG) { 821 Log.v(getTag(), "onMeasure result " + result[0] + ", " + result[1] 822 + " mItemLengthSecondary " + mItemLengthSecondary + " mNumRows " + mNumRows); 823 } 824 } 825 826 private void measureChild(View child) { 827 final ViewGroup.LayoutParams lp = child.getLayoutParams(); 828 829 int widthSpec, heightSpec; 830 if (mOrientation == HORIZONTAL) { 831 widthSpec = ViewGroup.getChildMeasureSpec( 832 MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 0, lp.width); 833 heightSpec = ViewGroup.getChildMeasureSpec(MeasureSpec.makeMeasureSpec( 834 mItemLengthSecondary, MeasureSpec.EXACTLY), 0, lp.height); 835 } else { 836 heightSpec = ViewGroup.getChildMeasureSpec( 837 MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 0, lp.height); 838 widthSpec = ViewGroup.getChildMeasureSpec(MeasureSpec.makeMeasureSpec( 839 mItemLengthSecondary, MeasureSpec.EXACTLY), 0, lp.width); 840 } 841 842 child.measure(widthSpec, heightSpec); 843 } 844 845 private StaggeredGrid.Provider mGridProvider = new StaggeredGrid.Provider() { 846 847 @Override 848 public int getCount() { 849 return mAdapter.getItemCount(); 850 } 851 852 @Override 853 public void createItem(int index, int rowIndex, boolean append) { 854 View v = getViewForPosition(index); 855 if (mFirstVisiblePos >= 0) { 856 // when StaggeredGrid append or prepend item, we must guarantee 857 // that sibling item has created views already. 858 if (append && index != mLastVisiblePos + 1) { 859 throw new RuntimeException(); 860 } else if (!append && index != mFirstVisiblePos - 1) { 861 throw new RuntimeException(); 862 } 863 } 864 865 if (append) { 866 addView(v); 867 } else { 868 addView(v, 0); 869 } 870 871 measureChild(v); 872 873 int length = mOrientation == HORIZONTAL ? v.getMeasuredWidth() : v.getMeasuredHeight(); 874 int start, end; 875 if (append) { 876 start = mRows[rowIndex].high; 877 if (start != mRows[rowIndex].low) { 878 // if there are existing item in the row, add margin between 879 start += mMarginPrimary; 880 } else { 881 final int lastRow = mRows.length - 1; 882 if (lastRow != rowIndex && mRows[lastRow].high != mRows[lastRow].low) { 883 // if there are existing item in the last row, insert 884 // the new item after the last item of last row. 885 start = mRows[lastRow].high + mMarginPrimary; 886 } 887 } 888 end = start + length; 889 mRows[rowIndex].high = end; 890 } else { 891 end = mRows[rowIndex].low; 892 if (end != mRows[rowIndex].high) { 893 end -= mMarginPrimary; 894 } else if (0 != rowIndex && mRows[0].high != mRows[0].low) { 895 // if there are existing item in the first row, insert 896 // the new item before the first item of first row. 897 end = mRows[0].low - mMarginPrimary; 898 } 899 start = end - length; 900 mRows[rowIndex].low = start; 901 } 902 if (mFirstVisiblePos < 0) { 903 mFirstVisiblePos = mLastVisiblePos = index; 904 } else { 905 if (append) { 906 mLastVisiblePos++; 907 } else { 908 mFirstVisiblePos--; 909 } 910 } 911 int startSecondary = rowIndex * (mItemLengthSecondary + mMarginSecondary); 912 layoutChild(v, start - mScrollOffsetPrimary, end - mScrollOffsetPrimary, 913 startSecondary - mScrollOffsetSecondary); 914 if (DEBUG) { 915 Log.d(getTag(), "addView " + index + " " + v); 916 } 917 updateScrollMin(); 918 updateScrollMax(); 919 } 920 }; 921 922 private void layoutChild(View v, int start, int end, int startSecondary) { 923 int measuredSecondary = mOrientation == HORIZONTAL ? v.getMeasuredHeight() 924 : v.getMeasuredWidth(); 925 if (measuredSecondary > mItemLengthSecondary) { 926 measuredSecondary = mItemLengthSecondary; 927 } 928 final int verticalGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 929 final int horizontalGravity = mGravity & Gravity.HORIZONTAL_GRAVITY_MASK; 930 if (mOrientation == HORIZONTAL && verticalGravity == Gravity.TOP 931 || mOrientation == VERTICAL && horizontalGravity == Gravity.LEFT) { 932 // do nothing 933 } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.BOTTOM 934 || mOrientation == VERTICAL && horizontalGravity == Gravity.RIGHT) { 935 startSecondary += mItemLengthSecondary - measuredSecondary; 936 } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.CENTER_VERTICAL 937 || mOrientation == VERTICAL && horizontalGravity == Gravity.CENTER_HORIZONTAL) { 938 startSecondary += (mItemLengthSecondary - measuredSecondary) / 2; 939 } 940 if (mOrientation == HORIZONTAL) { 941 v.layout(start, startSecondary, end, startSecondary + measuredSecondary); 942 } else { 943 v.layout(startSecondary, start, startSecondary + measuredSecondary, end); 944 } 945 updateChildAlignments(v); 946 } 947 948 private void updateChildAlignments(View v) { 949 LayoutParams p = (LayoutParams) v.getLayoutParams(); 950 p.setAlignX(mItemAlignment.horizontal.getAlignmentPosition(v)); 951 p.setAlignY(mItemAlignment.vertical.getAlignmentPosition(v)); 952 } 953 954 private void updateChildAlignments() { 955 for (int i = 0, c = getChildCount(); i < c; i++) { 956 updateChildAlignments(getChildAt(i)); 957 } 958 } 959 960 private boolean needsAppendVisibleItem() { 961 if (mLastVisiblePos < mFocusPosition) { 962 return true; 963 } 964 int right = mScrollOffsetPrimary + mSizePrimary; 965 for (int i = 0; i < mNumRows; i++) { 966 if (mRows[i].low == mRows[i].high) { 967 if (mRows[i].high < right) { 968 return true; 969 } 970 } else if (mRows[i].high < right - mMarginPrimary) { 971 return true; 972 } 973 } 974 return false; 975 } 976 977 private boolean needsPrependVisibleItem() { 978 if (mFirstVisiblePos > mFocusPosition) { 979 return true; 980 } 981 for (int i = 0; i < mNumRows; i++) { 982 if (mRows[i].low == mRows[i].high) { 983 if (mRows[i].low > mScrollOffsetPrimary) { 984 return true; 985 } 986 } else if (mRows[i].low - mMarginPrimary > mScrollOffsetPrimary) { 987 return true; 988 } 989 } 990 return false; 991 } 992 993 // Append one column if possible and return true if reach end. 994 private boolean appendOneVisibleItem() { 995 while (true) { 996 if (mLastVisiblePos >= 0 && mLastVisiblePos < mGrid.getLastIndex()) { 997 // append invisible view of saved location till last row 998 final int index = mLastVisiblePos + 1; 999 final int row = mGrid.getLocation(index).row; 1000 mGridProvider.createItem(index, row, true); 1001 if (row == mNumRows - 1) { 1002 return false; 1003 } 1004 } else if (mLastVisiblePos < mAdapter.getItemCount() - 1) { 1005 mGrid.appendItems(mScrollOffsetPrimary + mSizePrimary); 1006 return false; 1007 } else { 1008 return true; 1009 } 1010 } 1011 } 1012 1013 private void appendVisibleItems() { 1014 while (needsAppendVisibleItem()) { 1015 if (appendOneVisibleItem()) { 1016 break; 1017 } 1018 } 1019 } 1020 1021 // Prepend one column if possible and return true if reach end. 1022 private boolean prependOneVisibleItem() { 1023 while (true) { 1024 if (mFirstVisiblePos > 0) { 1025 if (mFirstVisiblePos > mGrid.getFirstIndex()) { 1026 // prepend invisible view of saved location till first row 1027 final int index = mFirstVisiblePos - 1; 1028 final int row = mGrid.getLocation(index).row; 1029 mGridProvider.createItem(index, row, false); 1030 if (row == 0) { 1031 return false; 1032 } 1033 } else { 1034 mGrid.prependItems(mScrollOffsetPrimary); 1035 return false; 1036 } 1037 } else { 1038 return true; 1039 } 1040 } 1041 } 1042 1043 private void prependVisibleItems() { 1044 while (needsPrependVisibleItem()) { 1045 if (prependOneVisibleItem()) { 1046 break; 1047 } 1048 } 1049 } 1050 1051 private void removeChildAt(int position) { 1052 View v = getViewByPosition(position); 1053 if (v != null) { 1054 if (DEBUG) { 1055 Log.d(getTag(), "removeAndRecycleViewAt " + position); 1056 } 1057 ((LayoutParams) v.getLayoutParams()).onViewDetached(); 1058 removeAndRecycleViewAt(getIndexByPosition(position), mRecycler); 1059 } 1060 } 1061 1062 private void removeInvisibleViewsAtEnd() { 1063 boolean update = false; 1064 while(mLastVisiblePos > mFirstVisiblePos && mLastVisiblePos > mFocusPosition) { 1065 View view = getViewByPosition(mLastVisiblePos); 1066 if (getViewMin(view) > mSizePrimary) { 1067 removeChildAt(mLastVisiblePos); 1068 mLastVisiblePos--; 1069 update = true; 1070 } else { 1071 break; 1072 } 1073 } 1074 if (update) { 1075 updateRowsMinMax(); 1076 } 1077 } 1078 1079 private void removeInvisibleViewsAtFront() { 1080 boolean update = false; 1081 while(mLastVisiblePos > mFirstVisiblePos && mFirstVisiblePos < mFocusPosition) { 1082 View view = getViewByPosition(mFirstVisiblePos); 1083 if (getViewMax(view) < 0) { 1084 removeChildAt(mFirstVisiblePos); 1085 mFirstVisiblePos++; 1086 update = true; 1087 } else { 1088 break; 1089 } 1090 } 1091 if (update) { 1092 updateRowsMinMax(); 1093 } 1094 } 1095 1096 private void updateRowsMinMax() { 1097 if (mFirstVisiblePos < 0) { 1098 return; 1099 } 1100 for (int i = 0; i < mNumRows; i++) { 1101 mRows[i].low = Integer.MAX_VALUE; 1102 mRows[i].high = Integer.MIN_VALUE; 1103 } 1104 for (int i = mFirstVisiblePos; i <= mLastVisiblePos; i++) { 1105 View view = getViewByPosition(i); 1106 int row = mGrid.getLocation(i).row; 1107 int low = getViewMin(view) + mScrollOffsetPrimary; 1108 if (low < mRows[row].low) { 1109 mRows[row].low = low; 1110 } 1111 int high = getViewMax(view) + mScrollOffsetPrimary; 1112 if (high > mRows[row].high) { 1113 mRows[row].high = high; 1114 } 1115 } 1116 } 1117 1118 /** 1119 * Relayout and re-positioning child for a possible new size and/or a new 1120 * start. 1121 * 1122 * @param view View to measure and layout. 1123 * @param start New start of the view or Integer.MIN_VALUE for not change. 1124 * @return New start of next view. 1125 */ 1126 private int updateChildView(View view, int start, int startSecondary) { 1127 if (start == Integer.MIN_VALUE) { 1128 start = getViewMin(view); 1129 } 1130 int end; 1131 if (mOrientation == HORIZONTAL) { 1132 if (view.isLayoutRequested() || view.getMeasuredHeight() != mItemLengthSecondary) { 1133 measureChild(view); 1134 } 1135 end = start + view.getMeasuredWidth(); 1136 } else { 1137 if (view.isLayoutRequested() || view.getMeasuredWidth() != mItemLengthSecondary) { 1138 measureChild(view); 1139 } 1140 end = start + view.getMeasuredHeight(); 1141 } 1142 1143 layoutChild(view, start, end, startSecondary); 1144 return end + mMarginPrimary; 1145 } 1146 1147 // Fast layout when there is no structure change, adapter change, etc. 1148 protected void fastRelayout() { 1149 initScrollController(); 1150 1151 List<Integer>[] rows = mGrid.getItemPositionsInRows(mFirstVisiblePos, mLastVisiblePos); 1152 1153 // relayout and repositioning views on each row 1154 for (int i = 0; i < mNumRows; i++) { 1155 List<Integer> row = rows[i]; 1156 int start = Integer.MIN_VALUE; 1157 int startSecondary = 1158 i * (mItemLengthSecondary + mMarginSecondary) - mScrollOffsetSecondary; 1159 for (int j = 0, size = row.size(); j < size; j++) { 1160 int position = row.get(j); 1161 start = updateChildView(getViewByPosition(position), start, startSecondary); 1162 } 1163 } 1164 1165 appendVisibleItems(); 1166 prependVisibleItems(); 1167 1168 updateRowsMinMax(); 1169 updateScrollMin(); 1170 updateScrollMax(); 1171 1172 if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) { 1173 View focusView = getViewByPosition(mFocusPosition == NO_POSITION ? 0 : mFocusPosition); 1174 scrollToView(focusView, false); 1175 } 1176 } 1177 1178 // Lays out items based on the current scroll position 1179 @Override 1180 public void layoutChildren(RecyclerView.Adapter adapter, RecyclerView.Recycler recycler, 1181 boolean structureChanged) { 1182 if (DEBUG) { 1183 Log.v(getTag(), "layoutChildren start numRows " + mNumRows + " mScrollOffsetSecondary " 1184 + mScrollOffsetSecondary + " mScrollOffsetPrimary " + mScrollOffsetPrimary 1185 + " structureChanged " + structureChanged 1186 + " mForceFullLayout " + mForceFullLayout); 1187 Log.v(getTag(), "width " + getWidth() + " height " + getHeight()); 1188 } 1189 1190 if (mNumRows == 0) { 1191 // haven't done measure yet 1192 return; 1193 } 1194 final int itemCount = adapter.getItemCount(); 1195 if (itemCount < 0) { 1196 return; 1197 } 1198 1199 mInLayout = true; 1200 1201 // Track the old focus view so we can adjust our system scroll position 1202 // so that any scroll animations happening now will remain valid. 1203 int delta = 0, deltaSecondary = 0; 1204 if (mFocusPosition != NO_POSITION 1205 && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) { 1206 View focusView = getViewByPosition(mFocusPosition); 1207 if (focusView != null) { 1208 delta = mWindowAlignment.mainAxis().getSystemScrollPos( 1209 getViewCenter(focusView) + mScrollOffsetPrimary) - mScrollOffsetPrimary; 1210 deltaSecondary = 1211 mWindowAlignment.secondAxis().getSystemScrollPos( 1212 getViewCenterSecondary(focusView) + mScrollOffsetSecondary) 1213 - mScrollOffsetSecondary; 1214 } 1215 } 1216 1217 boolean hasDoneFirstLayout = hasDoneFirstLayout(); 1218 if (!structureChanged && !mForceFullLayout && hasDoneFirstLayout) { 1219 fastRelayout(); 1220 } else { 1221 boolean hadFocus = mBaseGridView.hasFocus(); 1222 1223 int newFocusPosition = init(adapter, recycler, mFocusPosition); 1224 if (DEBUG) { 1225 Log.v(getTag(), "mFocusPosition " + mFocusPosition + " newFocusPosition " 1226 + newFocusPosition); 1227 } 1228 1229 // depending on result of init(), either recreating everything 1230 // or try to reuse the row start positions near mFocusPosition 1231 if (mGrid.getSize() == 0) { 1232 // this is a fresh creating all items, starting from 1233 // mFocusPosition with a estimated row index. 1234 mGrid.setStart(newFocusPosition, StaggeredGrid.START_DEFAULT); 1235 1236 // Can't track the old focus view 1237 delta = deltaSecondary = 0; 1238 1239 } else { 1240 // mGrid remembers Locations for the column that 1241 // contains mFocusePosition and also mRows remembers start 1242 // positions of each row. 1243 // Manually re-create child views for that column 1244 int firstIndex = mGrid.getFirstIndex(); 1245 int lastIndex = mGrid.getLastIndex(); 1246 for (int i = firstIndex; i <= lastIndex; i++) { 1247 mGridProvider.createItem(i, mGrid.getLocation(i).row, true); 1248 } 1249 } 1250 // add visible views at end until reach the end of window 1251 appendVisibleItems(); 1252 // add visible views at front until reach the start of window 1253 prependVisibleItems(); 1254 // multiple rounds: scrollToView of first round may drag first/last child into 1255 // "visible window" and we update scrollMin/scrollMax then run second scrollToView 1256 int oldFirstVisible; 1257 int oldLastVisible; 1258 do { 1259 oldFirstVisible = mFirstVisiblePos; 1260 oldLastVisible = mLastVisiblePos; 1261 View focusView = getViewByPosition(newFocusPosition); 1262 // we need force to initialize the child view's position 1263 scrollToView(focusView, false); 1264 if (focusView != null && hadFocus) { 1265 focusView.requestFocus(); 1266 } 1267 appendVisibleItems(); 1268 prependVisibleItems(); 1269 removeInvisibleViewsAtFront(); 1270 removeInvisibleViewsAtEnd(); 1271 } while (mFirstVisiblePos != oldFirstVisible || mLastVisiblePos != oldLastVisible); 1272 } 1273 mForceFullLayout = false; 1274 1275 if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED) { 1276 scrollDirectionPrimary(-delta); 1277 scrollDirectionSecondary(-deltaSecondary); 1278 } 1279 appendVisibleItems(); 1280 prependVisibleItems(); 1281 removeInvisibleViewsAtFront(); 1282 removeInvisibleViewsAtEnd(); 1283 1284 if (DEBUG) { 1285 StringWriter sw = new StringWriter(); 1286 PrintWriter pw = new PrintWriter(sw); 1287 mGrid.debugPrint(pw); 1288 Log.d(getTag(), sw.toString()); 1289 } 1290 1291 removeAndRecycleScrap(recycler); 1292 attemptAnimateLayoutChild(); 1293 1294 if (!hasDoneFirstLayout) { 1295 dispatchChildSelected(); 1296 } 1297 mInLayout = false; 1298 if (DEBUG) Log.v(getTag(), "layoutChildren end"); 1299 } 1300 1301 private void offsetChildrenSecondary(int increment) { 1302 final int childCount = getChildCount(); 1303 if (mOrientation == HORIZONTAL) { 1304 for (int i = 0; i < childCount; i++) { 1305 getChildAt(i).offsetTopAndBottom(increment); 1306 } 1307 } else { 1308 for (int i = 0; i < childCount; i++) { 1309 getChildAt(i).offsetLeftAndRight(increment); 1310 } 1311 } 1312 mScrollOffsetSecondary -= increment; 1313 } 1314 1315 private void offsetChildrenPrimary(int increment) { 1316 final int childCount = getChildCount(); 1317 if (mOrientation == VERTICAL) { 1318 for (int i = 0; i < childCount; i++) { 1319 getChildAt(i).offsetTopAndBottom(increment); 1320 } 1321 } else { 1322 for (int i = 0; i < childCount; i++) { 1323 getChildAt(i).offsetLeftAndRight(increment); 1324 } 1325 } 1326 mScrollOffsetPrimary -= increment; 1327 } 1328 1329 @Override 1330 public int scrollHorizontallyBy(int dx, Adapter adapter, Recycler recycler) { 1331 if (DEBUG) Log.v(TAG, "scrollHorizontallyBy " + dx); 1332 1333 if (mOrientation == HORIZONTAL) { 1334 return scrollDirectionPrimary(dx); 1335 } else { 1336 return scrollDirectionSecondary(dx); 1337 } 1338 } 1339 1340 @Override 1341 public int scrollVerticallyBy(int dy, Adapter adapter, Recycler recycler) { 1342 if (DEBUG) Log.v(TAG, "scrollVerticallyBy " + dy); 1343 if (mOrientation == VERTICAL) { 1344 return scrollDirectionPrimary(dy); 1345 } else { 1346 return scrollDirectionSecondary(dy); 1347 } 1348 } 1349 1350 // scroll in main direction may add/prune views 1351 private int scrollDirectionPrimary(int da) { 1352 offsetChildrenPrimary(-da); 1353 if (mInLayout) { 1354 return da; 1355 } 1356 if (da > 0) { 1357 appendVisibleItems(); 1358 removeInvisibleViewsAtFront(); 1359 } else if (da < 0) { 1360 prependVisibleItems(); 1361 removeInvisibleViewsAtEnd(); 1362 } 1363 attemptAnimateLayoutChild(); 1364 mBaseGridView.invalidate(); 1365 return da; 1366 } 1367 1368 // scroll in second direction will not add/prune views 1369 private int scrollDirectionSecondary(int dy) { 1370 offsetChildrenSecondary(-dy); 1371 mBaseGridView.invalidate(); 1372 return dy; 1373 } 1374 1375 private void updateScrollMax() { 1376 if (mLastVisiblePos >= 0 && mLastVisiblePos == mAdapter.getItemCount() - 1) { 1377 int maxEdge = Integer.MIN_VALUE; 1378 for (int i = 0; i < mRows.length; i++) { 1379 if (mRows[i].high > maxEdge) { 1380 maxEdge = mRows[i].high; 1381 } 1382 } 1383 mWindowAlignment.mainAxis().setMaxEdge(maxEdge); 1384 if (DEBUG) Log.v(getTag(), "updating scroll maxEdge to " + maxEdge); 1385 } 1386 } 1387 1388 private void updateScrollMin() { 1389 if (mFirstVisiblePos == 0) { 1390 int minEdge = Integer.MAX_VALUE; 1391 for (int i = 0; i < mRows.length; i++) { 1392 if (mRows[i].low < minEdge) { 1393 minEdge = mRows[i].low; 1394 } 1395 } 1396 mWindowAlignment.mainAxis().setMinEdge(minEdge); 1397 if (DEBUG) Log.v(getTag(), "updating scroll minEdge to " + minEdge); 1398 } 1399 } 1400 1401 private void initScrollController() { 1402 mWindowAlignment.horizontal.setSize(getWidth()); 1403 mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight()); 1404 mWindowAlignment.vertical.setSize(getHeight()); 1405 mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom()); 1406 mSizePrimary = mWindowAlignment.mainAxis().getSize(); 1407 mWindowAlignment.mainAxis().invalidateScrollMin(); 1408 mWindowAlignment.mainAxis().invalidateScrollMax(); 1409 1410 // second axis min/max is determined at initialization, the mainAxis 1411 // min/max is determined later when we scroll to first or last item 1412 mWindowAlignment.secondAxis().setMinEdge(0); 1413 mWindowAlignment.secondAxis().setMaxEdge(mItemLengthSecondary * mNumRows + mMarginSecondary 1414 * (mNumRows - 1)); 1415 1416 if (DEBUG) { 1417 Log.v(getTag(), "initScrollController mSizePrimary " + mSizePrimary + " " 1418 + " mItemLengthSecondary " + mItemLengthSecondary + " " + mWindowAlignment); 1419 } 1420 } 1421 1422 public void setSelection(RecyclerView parent, int position) { 1423 setSelection(parent, position, false); 1424 } 1425 1426 public void setSelectionSmooth(RecyclerView parent, int position) { 1427 setSelection(parent, position, true); 1428 } 1429 1430 public int getSelection() { 1431 return mFocusPosition; 1432 } 1433 1434 public void setSelection(RecyclerView parent, int position, boolean smooth) { 1435 if (mFocusPosition == position) { 1436 return; 1437 } 1438 View view = getViewByPosition(position); 1439 if (view != null) { 1440 scrollToView(view, smooth); 1441 } else { 1442 boolean right = position > mFocusPosition; 1443 mFocusPosition = position; 1444 if (smooth) { 1445 if (!hasDoneFirstLayout()) { 1446 Log.w(getTag(), "setSelectionSmooth should " + 1447 "not be called before first layout pass"); 1448 return; 1449 } 1450 if (right) { 1451 appendVisibleItems(); 1452 } else { 1453 prependVisibleItems(); 1454 } 1455 scrollToView(getViewByPosition(position), smooth); 1456 } else { 1457 mForceFullLayout = true; 1458 parent.requestLayout(); 1459 } 1460 } 1461 } 1462 1463 @Override 1464 public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) { 1465 boolean needsLayout = false; 1466 if (itemCount != 0) { 1467 if (mFirstVisiblePos < 0) { 1468 needsLayout = true; 1469 } else if (!(positionStart > mLastVisiblePos + 1 || 1470 positionStart + itemCount < mFirstVisiblePos - 1)) { 1471 needsLayout = true; 1472 } 1473 } 1474 if (needsLayout) { 1475 recyclerView.requestLayout(); 1476 } 1477 } 1478 1479 @Override 1480 public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) { 1481 if (!mInLayout) { 1482 scrollToView(child, true); 1483 } 1484 return true; 1485 } 1486 1487 @Override 1488 public boolean requestChildRectangleOnScreen(RecyclerView parent, View view, Rect rect, 1489 boolean immediate) { 1490 if (DEBUG) Log.v(getTag(), "requestChildRectangleOnScreen " + view + " " + rect); 1491 return false; 1492 } 1493 1494 int getScrollOffsetX() { 1495 return mOrientation == HORIZONTAL ? mScrollOffsetPrimary : mScrollOffsetSecondary; 1496 } 1497 1498 int getScrollOffsetY() { 1499 return mOrientation == HORIZONTAL ? mScrollOffsetSecondary : mScrollOffsetPrimary; 1500 } 1501 1502 public void getViewSelectedOffsets(View view, int[] offsets) { 1503 int scrollOffsetX = getScrollOffsetX(); 1504 int scrollOffsetY = getScrollOffsetY(); 1505 int viewCenterX = scrollOffsetX + getViewCenterX(view); 1506 int viewCenterY = scrollOffsetY + getViewCenterY(view); 1507 offsets[0] = mWindowAlignment.horizontal.getSystemScrollPos(viewCenterX) - scrollOffsetX; 1508 offsets[1] = mWindowAlignment.vertical.getSystemScrollPos(viewCenterY) - scrollOffsetY; 1509 } 1510 1511 /** 1512 * Scroll to a given child view and change mFocusPosition. 1513 */ 1514 private void scrollToView(View view, boolean smooth) { 1515 int newFocusPosition = getPositionByView(view); 1516 if (mInLayout || newFocusPosition != mFocusPosition) { 1517 mFocusPosition = newFocusPosition; 1518 dispatchChildSelected(); 1519 } 1520 if (mBaseGridView.isChildrenDrawingOrderEnabledInternal()) { 1521 mBaseGridView.invalidate(); 1522 } 1523 if (view == null) { 1524 return; 1525 } 1526 if (!view.hasFocus() && mBaseGridView.hasFocus()) { 1527 // transfer focus to the child if it does not have focus yet (e.g. triggered 1528 // by setSelection()) 1529 view.requestFocus(); 1530 } 1531 switch (mFocusScrollStrategy) { 1532 case BaseGridView.FOCUS_SCROLL_ALIGNED: 1533 default: 1534 scrollToAlignedPosition(view, smooth); 1535 break; 1536 case BaseGridView.FOCUS_SCROLL_ITEM: 1537 case BaseGridView.FOCUS_SCROLL_PAGE: 1538 scrollItemOrPage(view, smooth); 1539 break; 1540 } 1541 } 1542 1543 private void scrollItemOrPage(View view, boolean smooth) { 1544 int pos = getPositionByView(view); 1545 int viewMin = getViewMin(view); 1546 int viewMax = getViewMax(view); 1547 // we either align "firstView" to left/top padding edge 1548 // or align "lastView" to right/bottom padding edge 1549 View firstView = null; 1550 View lastView = null; 1551 int paddingLow = mWindowAlignment.mainAxis().getPaddingLow(); 1552 int clientSize = mWindowAlignment.mainAxis().getClientSize(); 1553 final int row = mGrid.getLocation(pos).row; 1554 if (viewMin < paddingLow) { 1555 // view enters low padding area: 1556 firstView = view; 1557 if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) { 1558 // scroll one "page" left/top, 1559 // align first visible item of the "page" at the low padding edge. 1560 while (!prependOneVisibleItem()) { 1561 List<Integer> positions = 1562 mGrid.getItemPositionsInRows(mFirstVisiblePos, pos)[row]; 1563 firstView = getViewByPosition(positions.get(0)); 1564 if (viewMax - getViewMin(firstView) > clientSize) { 1565 if (positions.size() > 1) { 1566 firstView = getViewByPosition(positions.get(1)); 1567 } 1568 break; 1569 } 1570 } 1571 } 1572 } else if (viewMax > clientSize + paddingLow) { 1573 // view enters high padding area: 1574 if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) { 1575 // scroll whole one page right/bottom, align view at the low padding edge. 1576 firstView = view; 1577 do { 1578 List<Integer> positions = 1579 mGrid.getItemPositionsInRows(pos, mLastVisiblePos)[row]; 1580 lastView = getViewByPosition(positions.get(positions.size() - 1)); 1581 if (getViewMax(lastView) - viewMin > clientSize) { 1582 lastView = null; 1583 break; 1584 } 1585 } while (!appendOneVisibleItem()); 1586 if (lastView != null) { 1587 // however if we reached end, we should align last view. 1588 firstView = null; 1589 } 1590 } else { 1591 lastView = view; 1592 } 1593 } 1594 int scrollPrimary = 0; 1595 int scrollSecondary = 0; 1596 if (firstView != null) { 1597 scrollPrimary = getViewMin(firstView) - paddingLow; 1598 } else if (lastView != null) { 1599 scrollPrimary = getViewMax(lastView) - (paddingLow + clientSize); 1600 } 1601 View secondaryAlignedView; 1602 if (firstView != null) { 1603 secondaryAlignedView = firstView; 1604 } else if (lastView != null) { 1605 secondaryAlignedView = lastView; 1606 } else { 1607 secondaryAlignedView = view; 1608 } 1609 int viewCenterSecondary = mScrollOffsetSecondary + 1610 getViewCenterSecondary(secondaryAlignedView); 1611 mWindowAlignment.secondAxis().updateScrollCenter(viewCenterSecondary); 1612 scrollSecondary = mWindowAlignment.secondAxis().getSystemScrollPos(); 1613 scrollSecondary -= mScrollOffsetSecondary; 1614 scrollGrid(scrollPrimary, scrollSecondary, smooth); 1615 } 1616 1617 private void scrollToAlignedPosition(View view, boolean smooth) { 1618 int viewCenterPrimary = mScrollOffsetPrimary + getViewCenter(view); 1619 int viewCenterSecondary = mScrollOffsetSecondary + getViewCenterSecondary(view); 1620 if (DEBUG) { 1621 Log.v(getTag(), "scrollAligned smooth=" + smooth + " pos=" + mFocusPosition + " " 1622 + viewCenterPrimary +","+viewCenterSecondary + " " + mWindowAlignment); 1623 } 1624 1625 if (mInLayout || viewCenterPrimary != mWindowAlignment.mainAxis().getScrollCenter() 1626 || viewCenterSecondary != mWindowAlignment.secondAxis().getScrollCenter()) { 1627 mWindowAlignment.mainAxis().updateScrollCenter(viewCenterPrimary); 1628 mWindowAlignment.secondAxis().updateScrollCenter(viewCenterSecondary); 1629 int scrollPrimary = mWindowAlignment.mainAxis().getSystemScrollPos(); 1630 int scrollSecondary = mWindowAlignment.secondAxis().getSystemScrollPos(); 1631 if (DEBUG) { 1632 Log.v(getTag(), "scrollAligned " + scrollPrimary + " " + scrollSecondary 1633 +" " + mWindowAlignment); 1634 } 1635 1636 scrollPrimary -= mScrollOffsetPrimary; 1637 scrollSecondary -= mScrollOffsetSecondary; 1638 1639 scrollGrid(scrollPrimary, scrollSecondary, smooth); 1640 } 1641 } 1642 1643 private void scrollGrid(int scrollPrimary, int scrollSecondary, boolean smooth) { 1644 if (mInLayout) { 1645 scrollDirectionPrimary(scrollPrimary); 1646 scrollDirectionSecondary(scrollSecondary); 1647 } else { 1648 int scrollX; 1649 int scrollY; 1650 if (mOrientation == HORIZONTAL) { 1651 scrollX = scrollPrimary; 1652 scrollY = scrollSecondary; 1653 } else { 1654 scrollX = scrollSecondary; 1655 scrollY = scrollPrimary; 1656 } 1657 if (smooth) { 1658 mBaseGridView.smoothScrollBy(scrollX, scrollY); 1659 } else { 1660 mBaseGridView.scrollBy(scrollX, scrollY); 1661 } 1662 } 1663 } 1664 1665 public void setAnimateChildLayout(boolean animateChildLayout) { 1666 mAnimateChildLayout = animateChildLayout; 1667 if (!mAnimateChildLayout) { 1668 for (int i = 0, c = getChildCount(); i < c; i++) { 1669 ((LayoutParams) getChildAt(i).getLayoutParams()).endAnimate(); 1670 } 1671 } 1672 } 1673 1674 private void attemptAnimateLayoutChild() { 1675 for (int i = 0, c = getChildCount(); i < c; i++) { 1676 // TODO: start delay can be staggered 1677 View v = getChildAt(i); 1678 ((LayoutParams) v.getLayoutParams()).startAnimate(this, v, 0); 1679 } 1680 } 1681 1682 public boolean isChildLayoutAnimated() { 1683 return mAnimateChildLayout; 1684 } 1685 1686 public void setChildLayoutAnimationInterpolator(Interpolator interpolator) { 1687 mAnimateLayoutChildInterpolator = interpolator; 1688 } 1689 1690 public Interpolator getChildLayoutAnimationInterpolator() { 1691 return mAnimateLayoutChildInterpolator; 1692 } 1693 1694 public void setChildLayoutAnimationDuration(long duration) { 1695 mAnimateLayoutChildDuration = duration; 1696 } 1697 1698 public long getChildLayoutAnimationDuration() { 1699 return mAnimateLayoutChildDuration; 1700 } 1701 1702 private int findImmediateChildIndex(View view) { 1703 while (view != null && view != mBaseGridView) { 1704 int index = mBaseGridView.indexOfChild(view); 1705 if (index >= 0) { 1706 return index; 1707 } 1708 view = (View) view.getParent(); 1709 } 1710 return NO_POSITION; 1711 } 1712 1713 @Override 1714 public boolean onAddFocusables(RecyclerView recyclerView, 1715 ArrayList<View> views, int direction, int focusableMode) { 1716 // If this viewgroup or one of its children currently has focus then we 1717 // consider our children for focus searching in main direction on the same row. 1718 // If this viewgroup has no focus and using focus align, we want the system 1719 // to ignore our children and pass focus to the viewgroup, which will pass 1720 // focus on to its children appropriately. 1721 // If this viewgroup has no focus and not using focus align, we want to 1722 // consider the child that does not overlap with padding area. 1723 if (recyclerView.hasFocus()) { 1724 final int movement = getMovement(direction); 1725 if (movement != PREV_ITEM && movement != NEXT_ITEM) { 1726 // Move on secondary direction uses default addFocusables(). 1727 return false; 1728 } 1729 // Get current focus row. 1730 final View focused = recyclerView.findFocus(); 1731 final int focusedPos = getPositionByIndex(findImmediateChildIndex(focused)); 1732 final int focusedRow = mGrid != null && focusedPos != NO_POSITION ? 1733 mGrid.getLocation(focusedPos).row : NO_POSITION; 1734 // Add focusables within the same row. 1735 final int focusableCount = views.size(); 1736 if (mGrid != null) { 1737 // focusables will be the current focused view and next neighbor view of same row 1738 // on the focus search direction. 1739 for (int i = 0, count = getChildCount(); i < count; i++) { 1740 int index = movement == NEXT_ITEM ? i : count - 1 - i; 1741 final View child = getChildAt(index); 1742 if (child.getVisibility() != View.VISIBLE) { 1743 continue; 1744 } 1745 int position = getPositionByIndex(index); 1746 StaggeredGrid.Location loc = mGrid.getLocation(position); 1747 if (focusedRow == NO_POSITION || (loc != null && loc.row == focusedRow)) { 1748 if (focusedPos == NO_POSITION || 1749 (movement == NEXT_ITEM && position >= focusedPos) 1750 || (movement == PREV_ITEM && position <= focusedPos)) { 1751 child.addFocusables(views, direction, focusableMode); 1752 if (focusedPos != NO_POSITION && focusedPos != position) { 1753 break; 1754 } 1755 } 1756 } 1757 } 1758 } 1759 } else { 1760 if (mFocusScrollStrategy != BaseGridView.FOCUS_SCROLL_ALIGNED) { 1761 // adding views not overlapping padding area to avoid scrolling in gaining focus 1762 int left = mWindowAlignment.mainAxis().getPaddingLow(); 1763 int right = mWindowAlignment.mainAxis().getClientSize() + left; 1764 int size = views.size(); 1765 for (int i = 0, count = getChildCount(); i < count; i++) { 1766 View child = getChildAt(i); 1767 if (child.getVisibility() == View.VISIBLE) { 1768 if (getViewMin(child) >= left && getViewMax(child) <= right) { 1769 child.addFocusables(views, direction, focusableMode); 1770 } 1771 } 1772 } 1773 // if we cannot find any, then just add all children. 1774 if (views.size() == size) { 1775 for (int i = 0, count = getChildCount(); i < count; i++) { 1776 View child = getChildAt(i); 1777 if (child.getVisibility() == View.VISIBLE) { 1778 child.addFocusables(views, direction, focusableMode); 1779 } 1780 } 1781 } 1782 return true; 1783 } 1784 if (recyclerView.isFocusable()) { 1785 views.add(recyclerView); 1786 } 1787 } 1788 return true; 1789 } 1790 1791 @Override 1792 public View onFocusSearchFailed(View focused, int direction, Adapter adapter, 1793 Recycler recycler) { 1794 if (DEBUG) Log.v(getTag(), "onFocusSearchFailed direction " + direction); 1795 1796 View view = null; 1797 int movement = getMovement(direction); 1798 final FocusFinder ff = FocusFinder.getInstance(); 1799 if (movement == NEXT_ITEM) { 1800 while (view == null && !appendOneVisibleItem()) { 1801 view = ff.findNextFocus(mBaseGridView, focused, direction); 1802 } 1803 } else if (movement == PREV_ITEM){ 1804 while (view == null && !prependOneVisibleItem()) { 1805 view = ff.findNextFocus(mBaseGridView, focused, direction); 1806 } 1807 } 1808 if (view == null) { 1809 // returning the same view to prevent focus lost when scrolling past the end of the list 1810 if (movement == PREV_ITEM) { 1811 view = mFocusOutFront ? null : focused; 1812 } else if (movement == NEXT_ITEM){ 1813 view = mFocusOutEnd ? null : focused; 1814 } 1815 } 1816 if (DEBUG) Log.v(getTag(), "returning view " + view); 1817 return view; 1818 } 1819 1820 boolean gridOnRequestFocus(RecyclerView recyclerView, int direction, 1821 Rect previouslyFocusedRect) { 1822 switch (mFocusScrollStrategy) { 1823 case BaseGridView.FOCUS_SCROLL_ALIGNED: 1824 default: 1825 return gridOnRequestFocusAligned(recyclerView, direction, previouslyFocusedRect); 1826 case BaseGridView.FOCUS_SCROLL_PAGE: 1827 case BaseGridView.FOCUS_SCROLL_ITEM: 1828 return gridOnRequestFocusUnaligned(recyclerView, direction, previouslyFocusedRect); 1829 } 1830 } 1831 1832 private boolean gridOnRequestFocusAligned(RecyclerView recyclerView, int direction, 1833 Rect previouslyFocusedRect) { 1834 View view = getViewByPosition(mFocusPosition); 1835 if (view != null) { 1836 boolean result = view.requestFocus(direction, previouslyFocusedRect); 1837 if (!result && DEBUG) { 1838 Log.w(getTag(), "failed to request focus on " + view); 1839 } 1840 return result; 1841 } 1842 return false; 1843 } 1844 1845 private boolean gridOnRequestFocusUnaligned(RecyclerView recyclerView, int direction, 1846 Rect previouslyFocusedRect) { 1847 // focus to view not overlapping padding area to avoid scrolling in gaining focus 1848 int index; 1849 int increment; 1850 int end; 1851 int count = getChildCount(); 1852 if ((direction & View.FOCUS_FORWARD) != 0) { 1853 index = 0; 1854 increment = 1; 1855 end = count; 1856 } else { 1857 index = count - 1; 1858 increment = -1; 1859 end = -1; 1860 } 1861 int left = mWindowAlignment.mainAxis().getPaddingLow(); 1862 int right = mWindowAlignment.mainAxis().getClientSize() + left; 1863 for (int i = index; i != end; i += increment) { 1864 View child = getChildAt(i); 1865 if (child.getVisibility() == View.VISIBLE) { 1866 if (getViewMin(child) >= left && getViewMax(child) <= right) { 1867 if (child.requestFocus(direction, previouslyFocusedRect)) { 1868 return true; 1869 } 1870 } 1871 } 1872 } 1873 return false; 1874 } 1875 1876 private final static int PREV_ITEM = 0; 1877 private final static int NEXT_ITEM = 1; 1878 private final static int PREV_ROW = 2; 1879 private final static int NEXT_ROW = 3; 1880 1881 private int getMovement(int direction) { 1882 int movement = View.FOCUS_LEFT; 1883 1884 if (mOrientation == HORIZONTAL) { 1885 switch(direction) { 1886 case View.FOCUS_LEFT: 1887 movement = PREV_ITEM; 1888 break; 1889 case View.FOCUS_RIGHT: 1890 movement = NEXT_ITEM; 1891 break; 1892 case View.FOCUS_UP: 1893 movement = PREV_ROW; 1894 break; 1895 case View.FOCUS_DOWN: 1896 movement = NEXT_ROW; 1897 break; 1898 } 1899 } else if (mOrientation == VERTICAL) { 1900 switch(direction) { 1901 case View.FOCUS_LEFT: 1902 movement = PREV_ROW; 1903 break; 1904 case View.FOCUS_RIGHT: 1905 movement = NEXT_ROW; 1906 break; 1907 case View.FOCUS_UP: 1908 movement = PREV_ITEM; 1909 break; 1910 case View.FOCUS_DOWN: 1911 movement = NEXT_ITEM; 1912 break; 1913 } 1914 } 1915 1916 return movement; 1917 } 1918 1919 int getChildDrawingOrder(RecyclerView recyclerView, int childCount, int i) { 1920 int focusIndex = getIndexByPosition(mFocusPosition); 1921 if (focusIndex == NO_POSITION) { 1922 return i; 1923 } 1924 // supposely 0 1 2 3 4 5 6 7 8 9, 4 is the center item 1925 // drawing order is 0 1 2 3 9 8 7 6 5 4 1926 if (i < focusIndex) { 1927 return i; 1928 } else if (i < childCount - 1) { 1929 return focusIndex + childCount - 1 - i; 1930 } else { 1931 return focusIndex; 1932 } 1933 } 1934 1935 @Override 1936 public void onAdapterChanged(RecyclerView.Adapter oldAdapter, 1937 RecyclerView.Adapter newAdapter) { 1938 mGrid = null; 1939 mRows = null; 1940 super.onAdapterChanged(oldAdapter, newAdapter); 1941 } 1942 1943} 1944