GridLayoutManager.java revision ac6a1a35cff83fdb50d9c8e203f881a54e92e40c
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.util.CircularIntArray; 23import android.support.v4.view.ViewCompat; 24import android.support.v4.view.accessibility.AccessibilityEventCompat; 25import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; 26import android.support.v4.view.accessibility.AccessibilityRecordCompat; 27import android.support.v7.widget.LinearSmoothScroller; 28import android.support.v7.widget.RecyclerView; 29import android.support.v7.widget.RecyclerView.Recycler; 30import android.support.v7.widget.RecyclerView.State; 31import android.support.v17.leanback.os.TraceHelper; 32 33import static android.support.v7.widget.RecyclerView.NO_ID; 34import static android.support.v7.widget.RecyclerView.NO_POSITION; 35import static android.support.v7.widget.RecyclerView.HORIZONTAL; 36import static android.support.v7.widget.RecyclerView.VERTICAL; 37 38import android.util.AttributeSet; 39import android.util.Log; 40import android.view.FocusFinder; 41import android.view.Gravity; 42import android.view.View; 43import android.view.ViewParent; 44import android.view.View.MeasureSpec; 45import android.view.ViewGroup.MarginLayoutParams; 46import android.view.ViewGroup; 47 48import java.io.PrintWriter; 49import java.io.StringWriter; 50import java.util.ArrayList; 51import java.util.List; 52 53final class GridLayoutManager extends RecyclerView.LayoutManager { 54 55 /* 56 * LayoutParams for {@link HorizontalGridView} and {@link VerticalGridView}. 57 * The class currently does two internal jobs: 58 * - Saves optical bounds insets. 59 * - Caches focus align view center. 60 */ 61 final static class LayoutParams extends RecyclerView.LayoutParams { 62 63 // For placement 64 private int mLeftInset; 65 private int mTopInset; 66 private int mRightInset; 67 private int mBottomInset; 68 69 // For alignment 70 private int mAlignX; 71 private int mAlignY; 72 private int[] mAlignMultiple; 73 private ItemAlignmentFacet mAlignmentFacet; 74 75 public LayoutParams(Context c, AttributeSet attrs) { 76 super(c, attrs); 77 } 78 79 public LayoutParams(int width, int height) { 80 super(width, height); 81 } 82 83 public LayoutParams(MarginLayoutParams source) { 84 super(source); 85 } 86 87 public LayoutParams(ViewGroup.LayoutParams source) { 88 super(source); 89 } 90 91 public LayoutParams(RecyclerView.LayoutParams source) { 92 super(source); 93 } 94 95 public LayoutParams(LayoutParams source) { 96 super(source); 97 } 98 99 int getAlignX() { 100 return mAlignX; 101 } 102 103 int getAlignY() { 104 return mAlignY; 105 } 106 107 int getOpticalLeft(View view) { 108 return view.getLeft() + mLeftInset; 109 } 110 111 int getOpticalTop(View view) { 112 return view.getTop() + mTopInset; 113 } 114 115 int getOpticalRight(View view) { 116 return view.getRight() - mRightInset; 117 } 118 119 int getOpticalBottom(View view) { 120 return view.getBottom() - mBottomInset; 121 } 122 123 int getOpticalWidth(View view) { 124 return view.getWidth() - mLeftInset - mRightInset; 125 } 126 127 int getOpticalHeight(View view) { 128 return view.getHeight() - mTopInset - mBottomInset; 129 } 130 131 int getDecoratedOpticalLeftWithMargin(RecyclerView.LayoutManager lm, View view) { 132 return lm.getDecoratedLeft(view) + mLeftInset - leftMargin; 133 } 134 135 int getDecoratedOpticalTopWithMargin(RecyclerView.LayoutManager lm, View view) { 136 return lm.getDecoratedTop(view) + mTopInset - topMargin; 137 } 138 139 int getDecoratedOpticalRightWithMargin(RecyclerView.LayoutManager lm, View view) { 140 return lm.getDecoratedRight(view) - mRightInset + rightMargin; 141 } 142 143 int getDecoratedOpticalBottomWithMargin(RecyclerView.LayoutManager lm, View view) { 144 return lm.getDecoratedBottom(view) - mBottomInset + bottomMargin; 145 } 146 147 int getDecoratedOpticalWidthWithMargin(RecyclerView.LayoutManager lm, View view) { 148 return lm.getDecoratedRight(view) - lm.getDecoratedLeft(view) 149 - mLeftInset - mRightInset + leftMargin + rightMargin; 150 } 151 152 int getDecoratedOpticalHeightWithMargin(RecyclerView.LayoutManager lm, View view) { 153 return lm.getDecoratedBottom(view) - lm.getDecoratedTop(view) 154 - mTopInset - mBottomInset + topMargin + bottomMargin; 155 } 156 157 int getOpticalLeftInset() { 158 return mLeftInset; 159 } 160 161 int getOpticalRightInset() { 162 return mRightInset; 163 } 164 165 int getOpticalTopInset() { 166 return mTopInset; 167 } 168 169 int getOpticalBottomInset() { 170 return mBottomInset; 171 } 172 173 void setAlignX(int alignX) { 174 mAlignX = alignX; 175 } 176 177 void setAlignY(int alignY) { 178 mAlignY = alignY; 179 } 180 181 void setItemAlignmentFacet(ItemAlignmentFacet facet) { 182 mAlignmentFacet = facet; 183 } 184 185 ItemAlignmentFacet getItemAlignmentFacet() { 186 return mAlignmentFacet; 187 } 188 189 void calculateItemAlignments(int orientation, View view) { 190 ItemAlignmentFacet.ItemAlignmentDef[] defs = mAlignmentFacet.getAlignmentDefs(); 191 if (mAlignMultiple == null || mAlignMultiple.length != defs.length) { 192 mAlignMultiple = new int[defs.length]; 193 } 194 for (int i = 0; i < defs.length; i++) { 195 mAlignMultiple[i] = ItemAlignmentFacetHelper 196 .getAlignmentPosition(view, defs[i], orientation); 197 } 198 if (orientation == HORIZONTAL) { 199 mAlignX = mAlignMultiple[0]; 200 } else { 201 mAlignY = mAlignMultiple[0]; 202 } 203 } 204 205 int[] getAlignMultiple() { 206 return mAlignMultiple; 207 } 208 209 void setOpticalInsets(int leftInset, int topInset, int rightInset, int bottomInset) { 210 mLeftInset = leftInset; 211 mTopInset = topInset; 212 mRightInset = rightInset; 213 mBottomInset = bottomInset; 214 } 215 216 } 217 218 /** 219 * Base class which scrolls to selected view in onStop(). 220 */ 221 abstract class GridLinearSmoothScroller extends LinearSmoothScroller { 222 GridLinearSmoothScroller() { 223 super(mBaseGridView.getContext()); 224 } 225 226 @Override 227 protected void onStop() { 228 // onTargetFound() may not be called if we hit the "wall" first or get cancelled. 229 View targetView = findViewByPosition(getTargetPosition()); 230 if (targetView == null) { 231 if (getTargetPosition() >= 0) { 232 // if smooth scroller is stopped without target, immediately jumps 233 // to the target position. 234 scrollToSelection(mBaseGridView, getTargetPosition(), 0, false, 0); 235 } 236 super.onStop(); 237 return; 238 } 239 if (hasFocus()) { 240 mInSelection = true; 241 targetView.requestFocus(); 242 mInSelection = false; 243 } 244 dispatchChildSelected(); 245 super.onStop(); 246 } 247 248 @Override 249 protected void onTargetFound(View targetView, 250 RecyclerView.State state, Action action) { 251 if (getScrollPosition(targetView, null, sTwoInts)) { 252 int dx, dy; 253 if (mOrientation == HORIZONTAL) { 254 dx = sTwoInts[0]; 255 dy = sTwoInts[1]; 256 } else { 257 dx = sTwoInts[1]; 258 dy = sTwoInts[0]; 259 } 260 final int distance = (int) Math.sqrt(dx * dx + dy * dy); 261 final int time = calculateTimeForDeceleration(distance); 262 action.update(dx, dy, time, mDecelerateInterpolator); 263 } 264 } 265 } 266 267 /** 268 * The SmoothScroller that remembers pending DPAD keys and consume pending keys 269 * during scroll. 270 */ 271 final class PendingMoveSmoothScroller extends GridLinearSmoothScroller { 272 // -2 is a target position that LinearSmoothScroller can never find until 273 // consumePendingMovesXXX() sets real targetPosition. 274 final static int TARGET_UNDEFINED = -2; 275 // whether the grid is staggered. 276 private final boolean mStaggeredGrid; 277 // Number of pending movements on primary direction, negative if PREV_ITEM. 278 private int mPendingMoves; 279 280 PendingMoveSmoothScroller(int initialPendingMoves, boolean staggeredGrid) { 281 mPendingMoves = initialPendingMoves; 282 mStaggeredGrid = staggeredGrid; 283 setTargetPosition(TARGET_UNDEFINED); 284 } 285 286 void increasePendingMoves() { 287 if (mPendingMoves < MAX_PENDING_MOVES) { 288 mPendingMoves++; 289 } 290 } 291 292 void decreasePendingMoves() { 293 if (mPendingMoves > -MAX_PENDING_MOVES) { 294 mPendingMoves--; 295 } 296 } 297 298 /** 299 * Called before laid out an item when non-staggered grid can handle pending movements 300 * by skipping "mNumRows" per movement; staggered grid will have to wait the item 301 * has been laid out in consumePendingMovesAfterLayout(). 302 */ 303 void consumePendingMovesBeforeLayout() { 304 if (mStaggeredGrid || mPendingMoves == 0) { 305 return; 306 } 307 View newSelected = null; 308 int startPos = mPendingMoves > 0 ? mFocusPosition + mNumRows : 309 mFocusPosition - mNumRows; 310 for (int pos = startPos; mPendingMoves != 0; 311 pos = mPendingMoves > 0 ? pos + mNumRows: pos - mNumRows) { 312 View v = findViewByPosition(pos); 313 if (v == null) { 314 break; 315 } 316 if (!canScrollTo(v)) { 317 continue; 318 } 319 newSelected = v; 320 mFocusPosition = pos; 321 mSubFocusPosition = 0; 322 if (mPendingMoves > 0) { 323 mPendingMoves--; 324 } else { 325 mPendingMoves++; 326 } 327 } 328 if (newSelected != null && hasFocus()) { 329 mInSelection = true; 330 newSelected.requestFocus(); 331 mInSelection = false; 332 } 333 } 334 335 /** 336 * Called after laid out an item. Staggered grid should find view on same 337 * Row and consume pending movements. 338 */ 339 void consumePendingMovesAfterLayout() { 340 if (mStaggeredGrid && mPendingMoves != 0) { 341 // consume pending moves, focus to item on the same row. 342 mPendingMoves = processSelectionMoves(true, mPendingMoves); 343 } 344 if (mPendingMoves == 0 || (mPendingMoves > 0 && hasCreatedLastItem()) 345 || (mPendingMoves < 0 && hasCreatedFirstItem())) { 346 setTargetPosition(mFocusPosition); 347 stop(); 348 } 349 } 350 351 @Override 352 protected void updateActionForInterimTarget(Action action) { 353 if (mPendingMoves == 0) { 354 return; 355 } 356 super.updateActionForInterimTarget(action); 357 } 358 359 @Override 360 public PointF computeScrollVectorForPosition(int targetPosition) { 361 if (mPendingMoves == 0) { 362 return null; 363 } 364 int direction = (mReverseFlowPrimary ? mPendingMoves > 0 : mPendingMoves < 0) ? 365 -1 : 1; 366 if (mOrientation == HORIZONTAL) { 367 return new PointF(direction, 0); 368 } else { 369 return new PointF(0, direction); 370 } 371 } 372 373 @Override 374 protected void onStop() { 375 super.onStop(); 376 // if we hit wall, need clear the remaining pending moves. 377 mPendingMoves = 0; 378 mPendingMoveSmoothScroller = null; 379 View v = findViewByPosition(getTargetPosition()); 380 if (v != null) scrollToView(v, true); 381 } 382 }; 383 384 private static final String TAG = "GridLayoutManager"; 385 private static final boolean DEBUG = false; 386 private static final boolean TRACE = false; 387 388 // maximum pending movement in one direction. 389 private final static int MAX_PENDING_MOVES = 10; 390 391 private String getTag() { 392 return TAG + ":" + mBaseGridView.getId(); 393 } 394 395 private final BaseGridView mBaseGridView; 396 397 /** 398 * Note on conventions in the presence of RTL layout directions: 399 * Many properties and method names reference entities related to the 400 * beginnings and ends of things. In the presence of RTL flows, 401 * it may not be clear whether this is intended to reference a 402 * quantity that changes direction in RTL cases, or a quantity that 403 * does not. Here are the conventions in use: 404 * 405 * start/end: coordinate quantities - do reverse 406 * (optical) left/right: coordinate quantities - do not reverse 407 * low/high: coordinate quantities - do not reverse 408 * min/max: coordinate quantities - do not reverse 409 * scroll offset - coordinate quantities - do not reverse 410 * first/last: positional indices - do not reverse 411 * front/end: positional indices - do not reverse 412 * prepend/append: related to positional indices - do not reverse 413 * 414 * Note that although quantities do not reverse in RTL flows, their 415 * relationship does. In LTR flows, the first positional index is 416 * leftmost; in RTL flows, it is rightmost. Thus, anywhere that 417 * positional quantities are mapped onto coordinate quantities, 418 * the flow must be checked and the logic reversed. 419 */ 420 421 /** 422 * The orientation of a "row". 423 */ 424 private int mOrientation = HORIZONTAL; 425 426 private RecyclerView.State mState; 427 private RecyclerView.Recycler mRecycler; 428 429 private static final Rect sTempRect = new Rect(); 430 431 private boolean mInLayout; 432 private boolean mInScroll; 433 private boolean mInFastRelayout; 434 /** 435 * During full layout pass, when GridView had focus: onLayoutChildren will 436 * skip non-focusable child and adjust mFocusPosition. 437 */ 438 private boolean mInLayoutSearchFocus; 439 private boolean mInSelection = false; 440 441 private OnChildSelectedListener mChildSelectedListener = null; 442 443 private OnChildViewHolderSelectedListener mChildViewHolderSelectedListener = null; 444 445 private OnChildLaidOutListener mChildLaidOutListener = null; 446 447 /** 448 * The focused position, it's not the currently visually aligned position 449 * but it is the final position that we intend to focus on. If there are 450 * multiple setSelection() called, mFocusPosition saves last value. 451 */ 452 private int mFocusPosition = NO_POSITION; 453 454 /** 455 * A view can have mutliple alignment position, this is the index of which 456 * alignment is used, by default is 0. 457 */ 458 private int mSubFocusPosition = 0; 459 460 /** 461 * LinearSmoothScroller that consume pending DPAD movements. 462 */ 463 private PendingMoveSmoothScroller mPendingMoveSmoothScroller; 464 465 /** 466 * The offset to be applied to mFocusPosition, due to adapter change, on the next 467 * layout. Set to Integer.MIN_VALUE means we should stop adding delta to mFocusPosition 468 * until next layout cycler. 469 * TODO: This is somewhat duplication of RecyclerView getOldPosition() which is 470 * unfortunately cleared after prelayout. 471 */ 472 private int mFocusPositionOffset = 0; 473 474 /** 475 * Extra pixels applied on primary direction. 476 */ 477 private int mPrimaryScrollExtra; 478 479 /** 480 * Force a full layout under certain situations. E.g. Rows change, jump to invisible child. 481 */ 482 private boolean mForceFullLayout; 483 484 /** 485 * True if layout is enabled. 486 */ 487 private boolean mLayoutEnabled = true; 488 489 /** 490 * override child visibility 491 */ 492 private int mChildVisibility = -1; 493 494 /** 495 * The scroll offsets of the viewport relative to the entire view. 496 */ 497 private int mScrollOffsetPrimary; 498 private int mScrollOffsetSecondary; 499 500 /** 501 * User-specified row height/column width. Can be WRAP_CONTENT. 502 */ 503 private int mRowSizeSecondaryRequested; 504 505 /** 506 * The fixed size of each grid item in the secondary direction. This corresponds to 507 * the row height, equal for all rows. Grid items may have variable length 508 * in the primary direction. 509 */ 510 private int mFixedRowSizeSecondary; 511 512 /** 513 * Tracks the secondary size of each row. 514 */ 515 private int[] mRowSizeSecondary; 516 517 /** 518 * Flag controlling whether the current/next layout should 519 * be updating the secondary size of rows. 520 */ 521 private boolean mRowSecondarySizeRefresh; 522 523 /** 524 * The maximum measured size of the view. 525 */ 526 private int mMaxSizeSecondary; 527 528 /** 529 * Margin between items. 530 */ 531 private int mHorizontalMargin; 532 /** 533 * Margin between items vertically. 534 */ 535 private int mVerticalMargin; 536 /** 537 * Margin in main direction. 538 */ 539 private int mMarginPrimary; 540 /** 541 * Margin in second direction. 542 */ 543 private int mMarginSecondary; 544 /** 545 * How to position child in secondary direction. 546 */ 547 private int mGravity = Gravity.START | Gravity.TOP; 548 /** 549 * The number of rows in the grid. 550 */ 551 private int mNumRows; 552 /** 553 * Number of rows requested, can be 0 to be determined by parent size and 554 * rowHeight. 555 */ 556 private int mNumRowsRequested = 1; 557 558 /** 559 * Saves grid information of each view. 560 */ 561 Grid mGrid; 562 563 /** 564 * Focus Scroll strategy. 565 */ 566 private int mFocusScrollStrategy = BaseGridView.FOCUS_SCROLL_ALIGNED; 567 /** 568 * Defines how item view is aligned in the window. 569 */ 570 private final WindowAlignment mWindowAlignment = new WindowAlignment(); 571 572 /** 573 * Defines how item view is aligned. 574 */ 575 private final ItemAlignment mItemAlignment = new ItemAlignment(); 576 577 /** 578 * Dimensions of the view, width or height depending on orientation. 579 */ 580 private int mSizePrimary; 581 582 /** 583 * Pixels of extra space for layout item (outside the widget) 584 */ 585 private int mExtraLayoutSpace; 586 587 /** 588 * Allow DPAD key to navigate out at the front of the View (where position = 0), 589 * default is false. 590 */ 591 private boolean mFocusOutFront; 592 593 /** 594 * Allow DPAD key to navigate out at the end of the view, default is false. 595 */ 596 private boolean mFocusOutEnd; 597 598 /** 599 * True if focus search is disabled. 600 */ 601 private boolean mFocusSearchDisabled; 602 603 /** 604 * True if prune child, might be disabled during transition. 605 */ 606 private boolean mPruneChild = true; 607 608 /** 609 * True if scroll content, might be disabled during transition. 610 */ 611 private boolean mScrollEnabled = true; 612 613 /** 614 * Temporary variable: an int array of length=2. 615 */ 616 private static int[] sTwoInts = new int[2]; 617 618 /** 619 * Set to true for RTL layout in horizontal orientation 620 */ 621 private boolean mReverseFlowPrimary = false; 622 623 /** 624 * Set to true for RTL layout in vertical orientation 625 */ 626 private boolean mReverseFlowSecondary = false; 627 628 /** 629 * Temporaries used for measuring. 630 */ 631 private int[] mMeasuredDimension = new int[2]; 632 633 final ViewsStateBundle mChildrenStates = new ViewsStateBundle(); 634 635 /** 636 * Optional interface implemented by Adapter. 637 */ 638 private FacetProviderAdapter mFacetProviderAdapter; 639 640 public GridLayoutManager(BaseGridView baseGridView) { 641 mBaseGridView = baseGridView; 642 } 643 644 public void setOrientation(int orientation) { 645 if (orientation != HORIZONTAL && orientation != VERTICAL) { 646 if (DEBUG) Log.v(getTag(), "invalid orientation: " + orientation); 647 return; 648 } 649 650 mOrientation = orientation; 651 mWindowAlignment.setOrientation(orientation); 652 mItemAlignment.setOrientation(orientation); 653 mForceFullLayout = true; 654 } 655 656 public void onRtlPropertiesChanged(int layoutDirection) { 657 if (mOrientation == HORIZONTAL) { 658 mReverseFlowPrimary = layoutDirection == View.LAYOUT_DIRECTION_RTL; 659 mReverseFlowSecondary = false; 660 } else { 661 mReverseFlowSecondary = layoutDirection == View.LAYOUT_DIRECTION_RTL; 662 mReverseFlowPrimary = false; 663 } 664 mWindowAlignment.horizontal.setReversedFlow(layoutDirection == View.LAYOUT_DIRECTION_RTL); 665 } 666 667 public int getFocusScrollStrategy() { 668 return mFocusScrollStrategy; 669 } 670 671 public void setFocusScrollStrategy(int focusScrollStrategy) { 672 mFocusScrollStrategy = focusScrollStrategy; 673 } 674 675 public void setWindowAlignment(int windowAlignment) { 676 mWindowAlignment.mainAxis().setWindowAlignment(windowAlignment); 677 } 678 679 public int getWindowAlignment() { 680 return mWindowAlignment.mainAxis().getWindowAlignment(); 681 } 682 683 public void setWindowAlignmentOffset(int alignmentOffset) { 684 mWindowAlignment.mainAxis().setWindowAlignmentOffset(alignmentOffset); 685 } 686 687 public int getWindowAlignmentOffset() { 688 return mWindowAlignment.mainAxis().getWindowAlignmentOffset(); 689 } 690 691 public void setWindowAlignmentOffsetPercent(float offsetPercent) { 692 mWindowAlignment.mainAxis().setWindowAlignmentOffsetPercent(offsetPercent); 693 } 694 695 public float getWindowAlignmentOffsetPercent() { 696 return mWindowAlignment.mainAxis().getWindowAlignmentOffsetPercent(); 697 } 698 699 public void setItemAlignmentOffset(int alignmentOffset) { 700 mItemAlignment.mainAxis().setItemAlignmentOffset(alignmentOffset); 701 updateChildAlignments(); 702 } 703 704 public int getItemAlignmentOffset() { 705 return mItemAlignment.mainAxis().getItemAlignmentOffset(); 706 } 707 708 public void setItemAlignmentOffsetWithPadding(boolean withPadding) { 709 mItemAlignment.mainAxis().setItemAlignmentOffsetWithPadding(withPadding); 710 updateChildAlignments(); 711 } 712 713 public boolean isItemAlignmentOffsetWithPadding() { 714 return mItemAlignment.mainAxis().isItemAlignmentOffsetWithPadding(); 715 } 716 717 public void setItemAlignmentOffsetPercent(float offsetPercent) { 718 mItemAlignment.mainAxis().setItemAlignmentOffsetPercent(offsetPercent); 719 updateChildAlignments(); 720 } 721 722 public float getItemAlignmentOffsetPercent() { 723 return mItemAlignment.mainAxis().getItemAlignmentOffsetPercent(); 724 } 725 726 public void setItemAlignmentViewId(int viewId) { 727 mItemAlignment.mainAxis().setItemAlignmentViewId(viewId); 728 updateChildAlignments(); 729 } 730 731 public int getItemAlignmentViewId() { 732 return mItemAlignment.mainAxis().getItemAlignmentViewId(); 733 } 734 735 public void setFocusOutAllowed(boolean throughFront, boolean throughEnd) { 736 mFocusOutFront = throughFront; 737 mFocusOutEnd = throughEnd; 738 } 739 740 public void setNumRows(int numRows) { 741 if (numRows < 0) throw new IllegalArgumentException(); 742 mNumRowsRequested = numRows; 743 } 744 745 /** 746 * Set the row height. May be WRAP_CONTENT, or a size in pixels. 747 */ 748 public void setRowHeight(int height) { 749 if (height >= 0 || height == ViewGroup.LayoutParams.WRAP_CONTENT) { 750 mRowSizeSecondaryRequested = height; 751 } else { 752 throw new IllegalArgumentException("Invalid row height: " + height); 753 } 754 } 755 756 public void setItemMargin(int margin) { 757 mVerticalMargin = mHorizontalMargin = margin; 758 mMarginPrimary = mMarginSecondary = margin; 759 } 760 761 public void setVerticalMargin(int margin) { 762 if (mOrientation == HORIZONTAL) { 763 mMarginSecondary = mVerticalMargin = margin; 764 } else { 765 mMarginPrimary = mVerticalMargin = margin; 766 } 767 } 768 769 public void setHorizontalMargin(int margin) { 770 if (mOrientation == HORIZONTAL) { 771 mMarginPrimary = mHorizontalMargin = margin; 772 } else { 773 mMarginSecondary = mHorizontalMargin = margin; 774 } 775 } 776 777 public int getVerticalMargin() { 778 return mVerticalMargin; 779 } 780 781 public int getHorizontalMargin() { 782 return mHorizontalMargin; 783 } 784 785 public void setGravity(int gravity) { 786 mGravity = gravity; 787 } 788 789 protected boolean hasDoneFirstLayout() { 790 return mGrid != null; 791 } 792 793 public void setOnChildSelectedListener(OnChildSelectedListener listener) { 794 mChildSelectedListener = listener; 795 } 796 797 public void setOnChildViewHolderSelectedListener(OnChildViewHolderSelectedListener listener) { 798 mChildViewHolderSelectedListener = listener; 799 } 800 801 void setOnChildLaidOutListener(OnChildLaidOutListener listener) { 802 mChildLaidOutListener = listener; 803 } 804 805 private int getPositionByView(View view) { 806 if (view == null) { 807 return NO_POSITION; 808 } 809 LayoutParams params = (LayoutParams) view.getLayoutParams(); 810 if (params == null || params.isItemRemoved()) { 811 // when item is removed, the position value can be any value. 812 return NO_POSITION; 813 } 814 return params.getViewPosition(); 815 } 816 817 private int getSubPositionByView(View view, View childView) { 818 if (view == null || childView == null) { 819 return 0; 820 } 821 final LayoutParams lp = (LayoutParams) view.getLayoutParams(); 822 final ItemAlignmentFacet facet = lp.getItemAlignmentFacet(); 823 if (facet != null) { 824 final ItemAlignmentFacet.ItemAlignmentDef[] defs = facet.getAlignmentDefs(); 825 if (defs.length > 1) { 826 while (childView != view) { 827 int id = childView.getId(); 828 if (id != View.NO_ID) { 829 for (int i = 1; i < defs.length; i++) { 830 if (defs[i].getItemAlignmentFocusViewId() == id) { 831 return i; 832 } 833 } 834 } 835 childView = (View) childView.getParent(); 836 } 837 } 838 } 839 return 0; 840 } 841 842 private int getPositionByIndex(int index) { 843 return getPositionByView(getChildAt(index)); 844 } 845 846 private void dispatchChildSelected() { 847 if (mChildSelectedListener == null && mChildViewHolderSelectedListener == null) { 848 return; 849 } 850 851 if (TRACE) TraceHelper.beginSection("onChildSelected"); 852 View view = mFocusPosition == NO_POSITION ? null : findViewByPosition(mFocusPosition); 853 if (view != null) { 854 RecyclerView.ViewHolder vh = mBaseGridView.getChildViewHolder(view); 855 if (mChildSelectedListener != null) { 856 mChildSelectedListener.onChildSelected(mBaseGridView, view, mFocusPosition, 857 vh == null? NO_ID: vh.getItemId()); 858 } 859 if (mChildViewHolderSelectedListener != null) { 860 mChildViewHolderSelectedListener.onChildViewHolderSelected(mBaseGridView, vh, 861 mFocusPosition, mSubFocusPosition); 862 } 863 } else { 864 if (mChildSelectedListener != null) { 865 mChildSelectedListener.onChildSelected(mBaseGridView, null, NO_POSITION, NO_ID); 866 } 867 if (mChildViewHolderSelectedListener != null) { 868 mChildViewHolderSelectedListener.onChildViewHolderSelected(mBaseGridView, null, 869 NO_POSITION, 0); 870 } 871 } 872 if (TRACE) TraceHelper.endSection(); 873 874 // Children may request layout when a child selection event occurs (such as a change of 875 // padding on the current and previously selected rows). 876 // If in layout, a child requesting layout may have been laid out before the selection 877 // callback. 878 // If it was not, the child will be laid out after the selection callback. 879 // If so, the layout request will be honoured though the view system will emit a double- 880 // layout warning. 881 // If not in layout, we may be scrolling in which case the child layout request will be 882 // eaten by recyclerview. Post a requestLayout. 883 if (!mInLayout && !mBaseGridView.isLayoutRequested()) { 884 int childCount = getChildCount(); 885 for (int i = 0; i < childCount; i++) { 886 if (getChildAt(i).isLayoutRequested()) { 887 forceRequestLayout(); 888 break; 889 } 890 } 891 } 892 } 893 894 @Override 895 public boolean canScrollHorizontally() { 896 // We can scroll horizontally if we have horizontal orientation, or if 897 // we are vertical and have more than one column. 898 return mOrientation == HORIZONTAL || mNumRows > 1; 899 } 900 901 @Override 902 public boolean canScrollVertically() { 903 // We can scroll vertically if we have vertical orientation, or if we 904 // are horizontal and have more than one row. 905 return mOrientation == VERTICAL || mNumRows > 1; 906 } 907 908 @Override 909 public RecyclerView.LayoutParams generateDefaultLayoutParams() { 910 return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 911 ViewGroup.LayoutParams.WRAP_CONTENT); 912 } 913 914 @Override 915 public RecyclerView.LayoutParams generateLayoutParams(Context context, AttributeSet attrs) { 916 return new LayoutParams(context, attrs); 917 } 918 919 @Override 920 public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { 921 if (lp instanceof LayoutParams) { 922 return new LayoutParams((LayoutParams) lp); 923 } else if (lp instanceof RecyclerView.LayoutParams) { 924 return new LayoutParams((RecyclerView.LayoutParams) lp); 925 } else if (lp instanceof MarginLayoutParams) { 926 return new LayoutParams((MarginLayoutParams) lp); 927 } else { 928 return new LayoutParams(lp); 929 } 930 } 931 932 protected View getViewForPosition(int position) { 933 return mRecycler.getViewForPosition(position); 934 } 935 936 final int getOpticalLeft(View v) { 937 return ((LayoutParams) v.getLayoutParams()).getOpticalLeft(v); 938 } 939 940 final int getOpticalRight(View v) { 941 return ((LayoutParams) v.getLayoutParams()).getOpticalRight(v); 942 } 943 944 final int getOpticalTop(View v) { 945 return ((LayoutParams) v.getLayoutParams()).getOpticalTop(v); 946 } 947 948 final int getOpticalBottom(View v) { 949 return ((LayoutParams) v.getLayoutParams()).getOpticalBottom(v); 950 } 951 952 private int getViewMin(View v) { 953 LayoutParams lp = (LayoutParams) v.getLayoutParams(); 954 return (mOrientation == HORIZONTAL) ? lp.getDecoratedOpticalLeftWithMargin(this, v) 955 : lp.getDecoratedOpticalTopWithMargin(this, v); 956 } 957 958 private int getViewMax(View v) { 959 LayoutParams lp = (LayoutParams) v.getLayoutParams(); 960 return (mOrientation == HORIZONTAL) ? lp.getDecoratedOpticalRightWithMargin(this, v) 961 : lp.getDecoratedOpticalBottomWithMargin(this, v); 962 } 963 964 private int getViewPrimarySize(View view) { 965 LayoutParams p = (LayoutParams) view.getLayoutParams(); 966 return mOrientation == HORIZONTAL ? p.getDecoratedOpticalWidthWithMargin(this, view) 967 : p.getDecoratedOpticalHeightWithMargin(this, view); 968 } 969 970 private int getViewCenter(View view) { 971 return (mOrientation == HORIZONTAL) ? getViewCenterX(view) : getViewCenterY(view); 972 } 973 974 private int getViewCenterSecondary(View view) { 975 return (mOrientation == HORIZONTAL) ? getViewCenterY(view) : getViewCenterX(view); 976 } 977 978 private int getViewCenterX(View v) { 979 LayoutParams p = (LayoutParams) v.getLayoutParams(); 980 return p.getOpticalLeft(v) + p.getAlignX(); 981 } 982 983 private int getViewCenterY(View v) { 984 LayoutParams p = (LayoutParams) v.getLayoutParams(); 985 return p.getOpticalTop(v) + p.getAlignY(); 986 } 987 988 /** 989 * Save Recycler and State for convenience. Must be paired with leaveContext(). 990 */ 991 private void saveContext(Recycler recycler, State state) { 992 if (mRecycler != null || mState != null) { 993 Log.e(TAG, "Recycler information was not released, bug!"); 994 } 995 mRecycler = recycler; 996 mState = state; 997 } 998 999 /** 1000 * Discard saved Recycler and State. 1001 */ 1002 private void leaveContext() { 1003 mRecycler = null; 1004 mState = null; 1005 } 1006 1007 /** 1008 * Re-initialize data structures for a data change or handling invisible 1009 * selection. The method tries its best to preserve position information so 1010 * that staggered grid looks same before and after re-initialize. 1011 * @return true if can fastRelayout() 1012 */ 1013 private boolean layoutInit() { 1014 boolean focusViewWasInTree = mGrid != null && mFocusPosition >= 0 1015 && mFocusPosition >= mGrid.getFirstVisibleIndex() 1016 && mFocusPosition <= mGrid.getLastVisibleIndex(); 1017 final int newItemCount = mState.getItemCount(); 1018 if (newItemCount == 0) { 1019 mFocusPosition = NO_POSITION; 1020 mSubFocusPosition = 0; 1021 } else if (mFocusPosition >= newItemCount) { 1022 mFocusPosition = newItemCount - 1; 1023 mSubFocusPosition = 0; 1024 } else if (mFocusPosition == NO_POSITION && newItemCount > 0) { 1025 // if focus position is never set before, initialize it to 0 1026 mFocusPosition = 0; 1027 mSubFocusPosition = 0; 1028 } 1029 if (!mState.didStructureChange() && mGrid.getFirstVisibleIndex() >= 0 && 1030 !mForceFullLayout && mGrid != null && mGrid.getNumRows() == mNumRows) { 1031 updateScrollController(); 1032 updateScrollSecondAxis(); 1033 mGrid.setMargin(mMarginPrimary); 1034 if (!focusViewWasInTree && mFocusPosition != NO_POSITION) { 1035 mGrid.setStart(mFocusPosition); 1036 } 1037 return true; 1038 } else { 1039 mForceFullLayout = false; 1040 int firstVisibleIndex = focusViewWasInTree ? mGrid.getFirstVisibleIndex() : 0; 1041 1042 if (mGrid == null || mNumRows != mGrid.getNumRows() || 1043 mReverseFlowPrimary != mGrid.isReversedFlow()) { 1044 mGrid = Grid.createGrid(mNumRows); 1045 mGrid.setProvider(mGridProvider); 1046 mGrid.setReversedFlow(mReverseFlowPrimary); 1047 } 1048 initScrollController(); 1049 updateScrollSecondAxis(); 1050 mGrid.setMargin(mMarginPrimary); 1051 detachAndScrapAttachedViews(mRecycler); 1052 mGrid.resetVisibleIndex(); 1053 if (mFocusPosition == NO_POSITION) { 1054 mBaseGridView.clearFocus(); 1055 } 1056 mWindowAlignment.mainAxis().invalidateScrollMin(); 1057 mWindowAlignment.mainAxis().invalidateScrollMax(); 1058 if (focusViewWasInTree && firstVisibleIndex <= mFocusPosition) { 1059 // if focusView was in tree, we will add item from first visible item 1060 mGrid.setStart(firstVisibleIndex); 1061 } else { 1062 // if focusView was not in tree, it's probably because focus position jumped 1063 // far away from visible range, so use mFocusPosition as start 1064 mGrid.setStart(mFocusPosition); 1065 } 1066 return false; 1067 } 1068 } 1069 1070 private int getRowSizeSecondary(int rowIndex) { 1071 if (mFixedRowSizeSecondary != 0) { 1072 return mFixedRowSizeSecondary; 1073 } 1074 if (mRowSizeSecondary == null) { 1075 return 0; 1076 } 1077 return mRowSizeSecondary[rowIndex]; 1078 } 1079 1080 private int getRowStartSecondary(int rowIndex) { 1081 int start = 0; 1082 // Iterate from left to right, which is a different index traversal 1083 // in RTL flow 1084 if (mReverseFlowSecondary) { 1085 for (int i = mNumRows-1; i > rowIndex; i--) { 1086 start += getRowSizeSecondary(i) + mMarginSecondary; 1087 } 1088 } else { 1089 for (int i = 0; i < rowIndex; i++) { 1090 start += getRowSizeSecondary(i) + mMarginSecondary; 1091 } 1092 } 1093 return start; 1094 } 1095 1096 private int getSizeSecondary() { 1097 int rightmostIndex = mReverseFlowSecondary ? 0 : mNumRows - 1; 1098 return getRowStartSecondary(rightmostIndex) + getRowSizeSecondary(rightmostIndex); 1099 } 1100 1101 int getDecoratedMeasuredWidthWithMargin(View v) { 1102 final LayoutParams lp = (LayoutParams) v.getLayoutParams(); 1103 return getDecoratedMeasuredWidth(v) + lp.leftMargin + lp.rightMargin; 1104 } 1105 1106 int getDecoratedMeasuredHeightWithMargin(View v) { 1107 final LayoutParams lp = (LayoutParams) v.getLayoutParams(); 1108 return getDecoratedMeasuredHeight(v) + lp.topMargin + lp.bottomMargin; 1109 } 1110 1111 private void measureScrapChild(int position, int widthSpec, int heightSpec, 1112 int[] measuredDimension) { 1113 View view = mRecycler.getViewForPosition(position); 1114 if (view != null) { 1115 final LayoutParams p = (LayoutParams) view.getLayoutParams(); 1116 calculateItemDecorationsForChild(view, sTempRect); 1117 int widthUsed = p.leftMargin + p.rightMargin + sTempRect.left + sTempRect.right; 1118 int heightUsed = p.topMargin + p.bottomMargin + sTempRect.top + sTempRect.bottom; 1119 1120 int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec, 1121 getPaddingLeft() + getPaddingRight() + widthUsed, p.width); 1122 int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec, 1123 getPaddingTop() + getPaddingBottom() + heightUsed, p.height); 1124 view.measure(childWidthSpec, childHeightSpec); 1125 1126 measuredDimension[0] = getDecoratedMeasuredWidthWithMargin(view); 1127 measuredDimension[1] = getDecoratedMeasuredHeightWithMargin(view); 1128 mRecycler.recycleView(view); 1129 } 1130 } 1131 1132 private boolean processRowSizeSecondary(boolean measure) { 1133 if (mFixedRowSizeSecondary != 0 || mRowSizeSecondary == null) { 1134 return false; 1135 } 1136 1137 if (TRACE) TraceHelper.beginSection("processRowSizeSecondary"); 1138 CircularIntArray[] rows = mGrid == null ? null : mGrid.getItemPositionsInRows(); 1139 boolean changed = false; 1140 int scrapChildWidth = -1; 1141 int scrapChildHeight = -1; 1142 1143 for (int rowIndex = 0; rowIndex < mNumRows; rowIndex++) { 1144 CircularIntArray row = rows == null ? null : rows[rowIndex]; 1145 final int rowItemsPairCount = row == null ? 0 : row.size(); 1146 int rowSize = -1; 1147 for (int rowItemPairIndex = 0; rowItemPairIndex < rowItemsPairCount; 1148 rowItemPairIndex += 2) { 1149 final int rowIndexStart = row.get(rowItemPairIndex); 1150 final int rowIndexEnd = row.get(rowItemPairIndex + 1); 1151 for (int i = rowIndexStart; i <= rowIndexEnd; i++) { 1152 final View view = findViewByPosition(i); 1153 if (view == null) { 1154 continue; 1155 } 1156 if (measure && view.isLayoutRequested()) { 1157 measureChild(view); 1158 } 1159 final int secondarySize = mOrientation == HORIZONTAL ? 1160 getDecoratedMeasuredHeightWithMargin(view) 1161 : getDecoratedMeasuredWidthWithMargin(view); 1162 if (secondarySize > rowSize) { 1163 rowSize = secondarySize; 1164 } 1165 } 1166 } 1167 1168 final int itemCount = mState.getItemCount(); 1169 if (measure && rowSize < 0 && itemCount > 0) { 1170 if (scrapChildWidth < 0 && scrapChildHeight < 0) { 1171 int position; 1172 if (mFocusPosition == NO_POSITION) { 1173 position = 0; 1174 } else if (mFocusPosition >= itemCount) { 1175 position = itemCount - 1; 1176 } else { 1177 position = mFocusPosition; 1178 } 1179 measureScrapChild(position, 1180 MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 1181 MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 1182 mMeasuredDimension); 1183 scrapChildWidth = mMeasuredDimension[0]; 1184 scrapChildHeight = mMeasuredDimension[1]; 1185 if (DEBUG) Log.v(TAG, "measured scrap child: " + scrapChildWidth + 1186 " " + scrapChildHeight); 1187 } 1188 rowSize = mOrientation == HORIZONTAL ? scrapChildHeight : scrapChildWidth; 1189 } 1190 if (rowSize < 0) { 1191 rowSize = 0; 1192 } 1193 if (mRowSizeSecondary[rowIndex] != rowSize) { 1194 if (DEBUG) Log.v(getTag(), "row size secondary changed: " + mRowSizeSecondary[rowIndex] + 1195 ", " + rowSize); 1196 mRowSizeSecondary[rowIndex] = rowSize; 1197 changed = true; 1198 } 1199 } 1200 1201 if (TRACE) TraceHelper.endSection(); 1202 return changed; 1203 } 1204 1205 /** 1206 * Checks if we need to update row secondary sizes. 1207 */ 1208 private void updateRowSecondarySizeRefresh() { 1209 mRowSecondarySizeRefresh = processRowSizeSecondary(false); 1210 if (mRowSecondarySizeRefresh) { 1211 if (DEBUG) Log.v(getTag(), "mRowSecondarySizeRefresh now set"); 1212 forceRequestLayout(); 1213 } 1214 } 1215 1216 private void forceRequestLayout() { 1217 if (DEBUG) Log.v(getTag(), "forceRequestLayout"); 1218 // RecyclerView prevents us from requesting layout in many cases 1219 // (during layout, during scroll, etc.) 1220 // For secondary row size wrap_content support we currently need a 1221 // second layout pass to update the measured size after having measured 1222 // and added child views in layoutChildren. 1223 // Force the second layout by posting a delayed runnable. 1224 // TODO: investigate allowing a second layout pass, 1225 // or move child add/measure logic to the measure phase. 1226 ViewCompat.postOnAnimation(mBaseGridView, mRequestLayoutRunnable); 1227 } 1228 1229 private final Runnable mRequestLayoutRunnable = new Runnable() { 1230 @Override 1231 public void run() { 1232 if (DEBUG) Log.v(getTag(), "request Layout from runnable"); 1233 requestLayout(); 1234 } 1235 }; 1236 1237 @Override 1238 public void onMeasure(Recycler recycler, State state, int widthSpec, int heightSpec) { 1239 saveContext(recycler, state); 1240 1241 int sizePrimary, sizeSecondary, modeSecondary, paddingSecondary; 1242 int measuredSizeSecondary; 1243 if (mOrientation == HORIZONTAL) { 1244 sizePrimary = MeasureSpec.getSize(widthSpec); 1245 sizeSecondary = MeasureSpec.getSize(heightSpec); 1246 modeSecondary = MeasureSpec.getMode(heightSpec); 1247 paddingSecondary = getPaddingTop() + getPaddingBottom(); 1248 } else { 1249 sizeSecondary = MeasureSpec.getSize(widthSpec); 1250 sizePrimary = MeasureSpec.getSize(heightSpec); 1251 modeSecondary = MeasureSpec.getMode(widthSpec); 1252 paddingSecondary = getPaddingLeft() + getPaddingRight(); 1253 } 1254 if (DEBUG) Log.v(getTag(), "onMeasure widthSpec " + Integer.toHexString(widthSpec) + 1255 " heightSpec " + Integer.toHexString(heightSpec) + 1256 " modeSecondary " + Integer.toHexString(modeSecondary) + 1257 " sizeSecondary " + sizeSecondary + " " + this); 1258 1259 mMaxSizeSecondary = sizeSecondary; 1260 1261 if (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) { 1262 mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested; 1263 mFixedRowSizeSecondary = 0; 1264 1265 if (mRowSizeSecondary == null || mRowSizeSecondary.length != mNumRows) { 1266 mRowSizeSecondary = new int[mNumRows]; 1267 } 1268 1269 // Measure all current children and update cached row heights 1270 processRowSizeSecondary(true); 1271 1272 switch (modeSecondary) { 1273 case MeasureSpec.UNSPECIFIED: 1274 measuredSizeSecondary = getSizeSecondary() + paddingSecondary; 1275 break; 1276 case MeasureSpec.AT_MOST: 1277 measuredSizeSecondary = Math.min(getSizeSecondary() + paddingSecondary, 1278 mMaxSizeSecondary); 1279 break; 1280 case MeasureSpec.EXACTLY: 1281 measuredSizeSecondary = mMaxSizeSecondary; 1282 break; 1283 default: 1284 throw new IllegalStateException("wrong spec"); 1285 } 1286 1287 } else { 1288 switch (modeSecondary) { 1289 case MeasureSpec.UNSPECIFIED: 1290 if (mRowSizeSecondaryRequested == 0) { 1291 if (mOrientation == HORIZONTAL) { 1292 throw new IllegalStateException("Must specify rowHeight or view height"); 1293 } else { 1294 throw new IllegalStateException("Must specify columnWidth or view width"); 1295 } 1296 } 1297 mFixedRowSizeSecondary = mRowSizeSecondaryRequested; 1298 mNumRows = mNumRowsRequested == 0 ? 1 : mNumRowsRequested; 1299 measuredSizeSecondary = mFixedRowSizeSecondary * mNumRows + mMarginSecondary 1300 * (mNumRows - 1) + paddingSecondary; 1301 break; 1302 case MeasureSpec.AT_MOST: 1303 case MeasureSpec.EXACTLY: 1304 if (mNumRowsRequested == 0 && mRowSizeSecondaryRequested == 0) { 1305 mNumRows = 1; 1306 mFixedRowSizeSecondary = sizeSecondary - paddingSecondary; 1307 } else if (mNumRowsRequested == 0) { 1308 mFixedRowSizeSecondary = mRowSizeSecondaryRequested; 1309 mNumRows = (sizeSecondary + mMarginSecondary) 1310 / (mRowSizeSecondaryRequested + mMarginSecondary); 1311 } else if (mRowSizeSecondaryRequested == 0) { 1312 mNumRows = mNumRowsRequested; 1313 mFixedRowSizeSecondary = (sizeSecondary - paddingSecondary - mMarginSecondary 1314 * (mNumRows - 1)) / mNumRows; 1315 } else { 1316 mNumRows = mNumRowsRequested; 1317 mFixedRowSizeSecondary = mRowSizeSecondaryRequested; 1318 } 1319 measuredSizeSecondary = sizeSecondary; 1320 if (modeSecondary == MeasureSpec.AT_MOST) { 1321 int childrenSize = mFixedRowSizeSecondary * mNumRows + mMarginSecondary 1322 * (mNumRows - 1) + paddingSecondary; 1323 if (childrenSize < measuredSizeSecondary) { 1324 measuredSizeSecondary = childrenSize; 1325 } 1326 } 1327 break; 1328 default: 1329 throw new IllegalStateException("wrong spec"); 1330 } 1331 } 1332 if (mOrientation == HORIZONTAL) { 1333 setMeasuredDimension(sizePrimary, measuredSizeSecondary); 1334 } else { 1335 setMeasuredDimension(measuredSizeSecondary, sizePrimary); 1336 } 1337 if (DEBUG) { 1338 Log.v(getTag(), "onMeasure sizePrimary " + sizePrimary + 1339 " measuredSizeSecondary " + measuredSizeSecondary + 1340 " mFixedRowSizeSecondary " + mFixedRowSizeSecondary + 1341 " mNumRows " + mNumRows); 1342 } 1343 leaveContext(); 1344 } 1345 1346 private void measureChild(View child) { 1347 if (TRACE) TraceHelper.beginSection("measureChild"); 1348 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 1349 calculateItemDecorationsForChild(child, sTempRect); 1350 int widthUsed = lp.leftMargin + lp.rightMargin + sTempRect.left + sTempRect.right; 1351 int heightUsed = lp.topMargin + lp.bottomMargin + sTempRect.top + sTempRect.bottom; 1352 1353 final int secondarySpec = (mRowSizeSecondaryRequested == ViewGroup.LayoutParams.WRAP_CONTENT) ? 1354 MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) : 1355 MeasureSpec.makeMeasureSpec(mFixedRowSizeSecondary, MeasureSpec.EXACTLY); 1356 int widthSpec, heightSpec; 1357 1358 if (mOrientation == HORIZONTAL) { 1359 widthSpec = ViewGroup.getChildMeasureSpec( 1360 MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), widthUsed, lp.width); 1361 heightSpec = ViewGroup.getChildMeasureSpec(secondarySpec, heightUsed, lp.height); 1362 } else { 1363 heightSpec = ViewGroup.getChildMeasureSpec( 1364 MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), heightUsed, lp.height); 1365 widthSpec = ViewGroup.getChildMeasureSpec(secondarySpec, widthUsed, lp.width); 1366 } 1367 child.measure(widthSpec, heightSpec); 1368 if (DEBUG) Log.v(getTag(), "measureChild secondarySpec " + Integer.toHexString(secondarySpec) + 1369 " widthSpec " + Integer.toHexString(widthSpec) + 1370 " heightSpec " + Integer.toHexString(heightSpec) + 1371 " measuredWidth " + child.getMeasuredWidth() + 1372 " measuredHeight " + child.getMeasuredHeight()); 1373 if (DEBUG) Log.v(getTag(), "child lp width " + lp.width + " height " + lp.height); 1374 if (TRACE) TraceHelper.endSection(); 1375 } 1376 1377 /** 1378 * Get facet from the ViewHolder or the viewType. 1379 */ 1380 private <E> E getFacet(RecyclerView.ViewHolder vh, Class<? extends E> facetClass) { 1381 E facet = null; 1382 if (vh instanceof FacetProvider) { 1383 facet = (E) ((FacetProvider) vh).getFacet(facetClass); 1384 } 1385 if (facet == null && mFacetProviderAdapter != null) { 1386 FacetProvider p = mFacetProviderAdapter.getFacetProvider(vh.getItemViewType()); 1387 if (p != null) { 1388 facet = (E) p.getFacet(facetClass); 1389 } 1390 } 1391 return facet; 1392 } 1393 1394 private Grid.Provider mGridProvider = new Grid.Provider() { 1395 1396 @Override 1397 public int getCount() { 1398 return mState.getItemCount(); 1399 } 1400 1401 @Override 1402 public int createItem(int index, boolean append, Object[] item) { 1403 if (TRACE) TraceHelper.beginSection("createItem"); 1404 if (TRACE) TraceHelper.beginSection("getview"); 1405 View v = getViewForPosition(index); 1406 if (TRACE) TraceHelper.endSection(); 1407 LayoutParams lp = (LayoutParams) v.getLayoutParams(); 1408 RecyclerView.ViewHolder vh = mBaseGridView.getChildViewHolder(v); 1409 lp.setItemAlignmentFacet((ItemAlignmentFacet)getFacet(vh, ItemAlignmentFacet.class)); 1410 // See recyclerView docs: we don't need re-add scraped view if it was removed. 1411 if (!lp.isItemRemoved()) { 1412 if (TRACE) TraceHelper.beginSection("addView"); 1413 if (append) { 1414 addView(v); 1415 } else { 1416 addView(v, 0); 1417 } 1418 if (TRACE) TraceHelper.endSection(); 1419 if (mChildVisibility != -1) { 1420 v.setVisibility(mChildVisibility); 1421 } 1422 1423 if (mPendingMoveSmoothScroller != null) { 1424 mPendingMoveSmoothScroller.consumePendingMovesBeforeLayout(); 1425 } 1426 int subindex = getSubPositionByView(v, v.findFocus()); 1427 if (!mInLayout) { 1428 // when we are appending item during scroll pass and the item's position 1429 // matches the mFocusPosition, we should signal a childSelected event. 1430 // However if we are still running PendingMoveSmoothScroller, we defer and 1431 // signal the event in PendingMoveSmoothScroller.onStop(). This can 1432 // avoid lots of childSelected events during a long smooth scrolling and 1433 // increase performance. 1434 if (index == mFocusPosition && subindex == mSubFocusPosition 1435 && mPendingMoveSmoothScroller == null) { 1436 dispatchChildSelected(); 1437 } 1438 } else if (!mInFastRelayout) { 1439 // fastRelayout will dispatch event at end of onLayoutChildren(). 1440 // For full layout, two situations here: 1441 // 1. mInLayoutSearchFocus is false, dispatchChildSelected() at mFocusPosition. 1442 // 2. mInLayoutSearchFocus is true: dispatchChildSelected() on first child 1443 // equal to or after mFocusPosition that can take focus. 1444 if (!mInLayoutSearchFocus && index == mFocusPosition 1445 && subindex == mSubFocusPosition) { 1446 dispatchChildSelected(); 1447 } else if (mInLayoutSearchFocus && index >= mFocusPosition 1448 && v.hasFocusable()) { 1449 mFocusPosition = index; 1450 mSubFocusPosition = subindex; 1451 mInLayoutSearchFocus = false; 1452 dispatchChildSelected(); 1453 } 1454 } 1455 measureChild(v); 1456 } 1457 item[0] = v; 1458 return mOrientation == HORIZONTAL ? getDecoratedMeasuredWidthWithMargin(v) 1459 : getDecoratedMeasuredHeightWithMargin(v); 1460 } 1461 1462 @Override 1463 public void addItem(Object item, int index, int length, int rowIndex, int edge) { 1464 View v = (View) item; 1465 int start, end; 1466 if (edge == Integer.MIN_VALUE || edge == Integer.MAX_VALUE) { 1467 edge = !mGrid.isReversedFlow() ? mWindowAlignment.mainAxis().getPaddingLow() 1468 : mWindowAlignment.mainAxis().getSize() 1469 - mWindowAlignment.mainAxis().getPaddingHigh(); 1470 } 1471 boolean edgeIsMin = !mGrid.isReversedFlow(); 1472 if (edgeIsMin) { 1473 start = edge; 1474 end = edge + length; 1475 } else { 1476 start = edge - length; 1477 end = edge; 1478 } 1479 int startSecondary = getRowStartSecondary(rowIndex) - mScrollOffsetSecondary; 1480 mChildrenStates.loadView(v, index); 1481 layoutChild(rowIndex, v, start, end, startSecondary); 1482 if (DEBUG) { 1483 Log.d(getTag(), "addView " + index + " " + v); 1484 } 1485 if (TRACE) TraceHelper.endSection(); 1486 1487 if (index == mGrid.getFirstVisibleIndex()) { 1488 if (!mGrid.isReversedFlow()) { 1489 updateScrollMin(); 1490 } else { 1491 updateScrollMax(); 1492 } 1493 } 1494 if (index == mGrid.getLastVisibleIndex()) { 1495 if (!mGrid.isReversedFlow()) { 1496 updateScrollMax(); 1497 } else { 1498 updateScrollMin(); 1499 } 1500 } 1501 if (!mInLayout && mPendingMoveSmoothScroller != null) { 1502 mPendingMoveSmoothScroller.consumePendingMovesAfterLayout(); 1503 } 1504 if (mChildLaidOutListener != null) { 1505 RecyclerView.ViewHolder vh = mBaseGridView.getChildViewHolder(v); 1506 mChildLaidOutListener.onChildLaidOut(mBaseGridView, v, index, 1507 vh == null ? NO_ID : vh.getItemId()); 1508 } 1509 } 1510 1511 @Override 1512 public void removeItem(int index) { 1513 if (TRACE) TraceHelper.beginSection("removeItem"); 1514 View v = findViewByPosition(index); 1515 if (mInLayout) { 1516 detachAndScrapView(v, mRecycler); 1517 } else { 1518 removeAndRecycleView(v, mRecycler); 1519 } 1520 if (TRACE) TraceHelper.endSection(); 1521 } 1522 1523 @Override 1524 public int getEdge(int index) { 1525 if (mReverseFlowPrimary) { 1526 return getViewMax(findViewByPosition(index)); 1527 } else { 1528 return getViewMin(findViewByPosition(index)); 1529 } 1530 } 1531 1532 @Override 1533 public int getSize(int index) { 1534 return getViewPrimarySize(findViewByPosition(index)); 1535 } 1536 }; 1537 1538 private void layoutChild(int rowIndex, View v, int start, int end, int startSecondary) { 1539 if (TRACE) TraceHelper.beginSection("layoutChild"); 1540 int sizeSecondary = mOrientation == HORIZONTAL ? getDecoratedMeasuredHeightWithMargin(v) 1541 : getDecoratedMeasuredWidthWithMargin(v); 1542 if (mFixedRowSizeSecondary > 0) { 1543 sizeSecondary = Math.min(sizeSecondary, mFixedRowSizeSecondary); 1544 } 1545 final int verticalGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 1546 final int horizontalGravity = (mReverseFlowPrimary || mReverseFlowSecondary) ? 1547 Gravity.getAbsoluteGravity(mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK, View.LAYOUT_DIRECTION_RTL) : 1548 mGravity & Gravity.HORIZONTAL_GRAVITY_MASK; 1549 if (mOrientation == HORIZONTAL && verticalGravity == Gravity.TOP 1550 || mOrientation == VERTICAL && horizontalGravity == Gravity.LEFT) { 1551 // do nothing 1552 } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.BOTTOM 1553 || mOrientation == VERTICAL && horizontalGravity == Gravity.RIGHT) { 1554 startSecondary += getRowSizeSecondary(rowIndex) - sizeSecondary; 1555 } else if (mOrientation == HORIZONTAL && verticalGravity == Gravity.CENTER_VERTICAL 1556 || mOrientation == VERTICAL && horizontalGravity == Gravity.CENTER_HORIZONTAL) { 1557 startSecondary += (getRowSizeSecondary(rowIndex) - sizeSecondary) / 2; 1558 } 1559 int left, top, right, bottom; 1560 if (mOrientation == HORIZONTAL) { 1561 left = start; 1562 top = startSecondary; 1563 right = end; 1564 bottom = startSecondary + sizeSecondary; 1565 } else { 1566 top = start; 1567 left = startSecondary; 1568 bottom = end; 1569 right = startSecondary + sizeSecondary; 1570 } 1571 LayoutParams params = (LayoutParams) v.getLayoutParams(); 1572 layoutDecorated(v, left + params.leftMargin, top + params.topMargin, 1573 right - params.rightMargin, bottom - params.bottomMargin); 1574 updateChildOpticalInsets(v, left, top, right, bottom); 1575 updateChildAlignments(v); 1576 if (TRACE) TraceHelper.endSection(); 1577 } 1578 1579 private void updateChildOpticalInsets(View v, int left, int top, int right, int bottom) { 1580 LayoutParams p = (LayoutParams) v.getLayoutParams(); 1581 p.setOpticalInsets(left - v.getLeft(), top - v.getTop(), 1582 v.getRight() - right, v.getBottom() - bottom); 1583 } 1584 1585 private void updateChildAlignments(View v) { 1586 final LayoutParams p = (LayoutParams) v.getLayoutParams(); 1587 if (p.getItemAlignmentFacet() == null) { 1588 // Fallback to global settings on grid view 1589 p.setAlignX(mItemAlignment.horizontal.getAlignmentPosition(v)); 1590 p.setAlignY(mItemAlignment.vertical.getAlignmentPosition(v)); 1591 } else { 1592 // Use ItemAlignmentFacet defined on specific ViewHolder 1593 p.calculateItemAlignments(mOrientation, v); 1594 if (mOrientation == HORIZONTAL) { 1595 p.setAlignY(mItemAlignment.vertical.getAlignmentPosition(v)); 1596 } else { 1597 p.setAlignX(mItemAlignment.horizontal.getAlignmentPosition(v)); 1598 } 1599 } 1600 } 1601 1602 private void updateChildAlignments() { 1603 for (int i = 0, c = getChildCount(); i < c; i++) { 1604 updateChildAlignments(getChildAt(i)); 1605 } 1606 } 1607 1608 void setExtraLayoutSpace(int extraLayoutSpace) { 1609 if (mExtraLayoutSpace == extraLayoutSpace) { 1610 return; 1611 } else if (mExtraLayoutSpace < 0) { 1612 throw new IllegalArgumentException("ExtraLayoutSpace must >= 0"); 1613 } 1614 mExtraLayoutSpace = extraLayoutSpace; 1615 requestLayout(); 1616 } 1617 1618 int getExtraLayoutSpace() { 1619 return mExtraLayoutSpace; 1620 } 1621 1622 private void removeInvisibleViewsAtEnd() { 1623 if (mPruneChild) { 1624 mGrid.removeInvisibleItemsAtEnd(mFocusPosition, 1625 mReverseFlowPrimary ? -mExtraLayoutSpace : mSizePrimary + mExtraLayoutSpace); 1626 } 1627 } 1628 1629 private void removeInvisibleViewsAtFront() { 1630 if (mPruneChild) { 1631 mGrid.removeInvisibleItemsAtFront(mFocusPosition, 1632 mReverseFlowPrimary ? mSizePrimary + mExtraLayoutSpace: -mExtraLayoutSpace); 1633 } 1634 } 1635 1636 private boolean appendOneColumnVisibleItems() { 1637 return mGrid.appendOneColumnVisibleItems(); 1638 } 1639 1640 private boolean prependOneColumnVisibleItems() { 1641 return mGrid.prependOneColumnVisibleItems(); 1642 } 1643 1644 private void appendVisibleItems() { 1645 mGrid.appendVisibleItems(mReverseFlowPrimary ? -mExtraLayoutSpace 1646 : mSizePrimary + mExtraLayoutSpace); 1647 } 1648 1649 private void prependVisibleItems() { 1650 mGrid.prependVisibleItems(mReverseFlowPrimary ? mSizePrimary + mExtraLayoutSpace 1651 : -mExtraLayoutSpace); 1652 } 1653 1654 /** 1655 * Fast layout when there is no structure change, adapter change, etc. 1656 * It will layout all views was layout requested or updated, until hit a view 1657 * with different size, then it break and detachAndScrap all views after that. 1658 */ 1659 private void fastRelayout() { 1660 boolean invalidateAfter = false; 1661 final int childCount = getChildCount(); 1662 int position = -1; 1663 for (int index = 0; index < childCount; index++) { 1664 View view = getChildAt(index); 1665 position = getPositionByIndex(index); 1666 Grid.Location location = mGrid.getLocation(position); 1667 if (location == null) { 1668 if (DEBUG) Log.w(getTag(), "fastRelayout(): no Location at " + position); 1669 invalidateAfter = true; 1670 break; 1671 } 1672 1673 int startSecondary = getRowStartSecondary(location.row) - mScrollOffsetSecondary; 1674 int primarySize, end; 1675 int start = getViewMin(view); 1676 int oldPrimarySize = getViewPrimarySize(view); 1677 1678 LayoutParams lp = (LayoutParams) view.getLayoutParams(); 1679 if (lp.viewNeedsUpdate()) { 1680 int viewIndex = mBaseGridView.indexOfChild(view); 1681 detachAndScrapView(view, mRecycler); 1682 view = getViewForPosition(position); 1683 addView(view, viewIndex); 1684 } 1685 1686 if (view.isLayoutRequested()) { 1687 measureChild(view); 1688 } 1689 if (mOrientation == HORIZONTAL) { 1690 primarySize = getDecoratedMeasuredWidthWithMargin(view); 1691 end = start + primarySize; 1692 } else { 1693 primarySize = getDecoratedMeasuredHeightWithMargin(view); 1694 end = start + primarySize; 1695 } 1696 layoutChild(location.row, view, start, end, startSecondary); 1697 if (oldPrimarySize != primarySize) { 1698 // size changed invalidate remaining Locations 1699 if (DEBUG) Log.d(getTag(), "fastRelayout: view size changed at " + position); 1700 invalidateAfter = true; 1701 break; 1702 } 1703 } 1704 if (invalidateAfter) { 1705 final int savedLastPos = mGrid.getLastVisibleIndex(); 1706 mGrid.invalidateItemsAfter(position); 1707 if (mPruneChild) { 1708 // in regular prune child mode, we just append items up to edge limit 1709 appendVisibleItems(); 1710 if (mFocusPosition >= 0 && mFocusPosition <= savedLastPos) { 1711 // make sure add focus view back: the view might be outside edge limit 1712 // when there is delta in onLayoutChildren(). 1713 while (mGrid.getLastVisibleIndex() < mFocusPosition) { 1714 mGrid.appendOneColumnVisibleItems(); 1715 } 1716 } 1717 } else { 1718 // prune disabled(e.g. in RowsFragment transition): append all removed items 1719 while (mGrid.appendOneColumnVisibleItems() 1720 && mGrid.getLastVisibleIndex() < savedLastPos); 1721 } 1722 } 1723 updateScrollMin(); 1724 updateScrollMax(); 1725 updateScrollSecondAxis(); 1726 } 1727 1728 public void removeAndRecycleAllViews(RecyclerView.Recycler recycler) { 1729 if (TRACE) TraceHelper.beginSection("removeAndRecycleAllViews"); 1730 if (DEBUG) Log.v(TAG, "removeAndRecycleAllViews " + getChildCount()); 1731 for (int i = getChildCount() - 1; i >= 0; i--) { 1732 removeAndRecycleViewAt(i, recycler); 1733 } 1734 if (TRACE) TraceHelper.endSection(); 1735 } 1736 1737 // Lays out items based on the current scroll position 1738 @Override 1739 public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { 1740 if (DEBUG) { 1741 Log.v(getTag(), "layoutChildren start numRows " + mNumRows + " mScrollOffsetSecondary " 1742 + mScrollOffsetSecondary + " mScrollOffsetPrimary " + mScrollOffsetPrimary 1743 + " inPreLayout " + state.isPreLayout() 1744 + " didStructureChange " + state.didStructureChange() 1745 + " mForceFullLayout " + mForceFullLayout); 1746 Log.v(getTag(), "width " + getWidth() + " height " + getHeight()); 1747 } 1748 1749 if (mNumRows == 0) { 1750 // haven't done measure yet 1751 return; 1752 } 1753 final int itemCount = state.getItemCount(); 1754 if (itemCount < 0) { 1755 return; 1756 } 1757 1758 if (!mLayoutEnabled) { 1759 discardLayoutInfo(); 1760 removeAndRecycleAllViews(recycler); 1761 return; 1762 } 1763 mInLayout = true; 1764 1765 if (state.didStructureChange()) { 1766 // didStructureChange() == true means attached item has been removed/added. 1767 // scroll animation: we are unable to continue a scroll animation, 1768 // kill the scroll animation, and let ItemAnimation move the item to new position. 1769 // position smooth scroller: kill the animation and stop at final position. 1770 // pending smooth scroller: stop and scroll to current focus position. 1771 mBaseGridView.stopScroll(); 1772 } 1773 final boolean scrollToFocus = !isSmoothScrolling() 1774 && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED; 1775 if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) { 1776 mFocusPosition = mFocusPosition + mFocusPositionOffset; 1777 mSubFocusPosition = 0; 1778 } 1779 mFocusPositionOffset = 0; 1780 saveContext(recycler, state); 1781 1782 // Track the old focus view so we can adjust our system scroll position 1783 // so that any scroll animations happening now will remain valid. 1784 // We must use same delta in Pre Layout (if prelayout exists) and second layout. 1785 // So we cache the deltas in PreLayout and use it in second layout. 1786 int delta = 0, deltaSecondary = 0; 1787 if (mFocusPosition != NO_POSITION && scrollToFocus 1788 && mBaseGridView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) { 1789 // FIXME: we should get the remaining scroll animation offset from RecyclerView 1790 View focusView = findViewByPosition(mFocusPosition); 1791 if (focusView != null) { 1792 if (getScrollPosition(focusView, focusView.findFocus(), sTwoInts)) { 1793 delta = sTwoInts[0]; 1794 deltaSecondary = sTwoInts[1]; 1795 } 1796 } 1797 } 1798 1799 boolean hadFocus = mBaseGridView.hasFocus(); 1800 int savedFocusPos = mFocusPosition; 1801 if (mInFastRelayout = layoutInit()) { 1802 fastRelayout(); 1803 // appends items till focus position. 1804 if (mFocusPosition != NO_POSITION) { 1805 View focusView = findViewByPosition(mFocusPosition); 1806 if (focusView != null) { 1807 if (scrollToFocus) { 1808 scrollToView(focusView, false); 1809 } 1810 if (hadFocus && !focusView.hasFocus()) { 1811 focusView.requestFocus(); 1812 } 1813 } 1814 } 1815 } else { 1816 mInLayoutSearchFocus = hadFocus; 1817 if (mFocusPosition != NO_POSITION) { 1818 // appends items till focus position. 1819 while (appendOneColumnVisibleItems() 1820 && findViewByPosition(mFocusPosition) == null) ; 1821 } 1822 // multiple rounds: scrollToView of first round may drag first/last child into 1823 // "visible window" and we update scrollMin/scrollMax then run second scrollToView 1824 int oldFirstVisible; 1825 int oldLastVisible; 1826 do { 1827 updateScrollMin(); 1828 updateScrollMax(); 1829 oldFirstVisible = mGrid.getFirstVisibleIndex(); 1830 oldLastVisible = mGrid.getLastVisibleIndex(); 1831 View focusView = findViewByPosition(mFocusPosition); 1832 // we need force to initialize the child view's position 1833 scrollToView(focusView, false); 1834 if (focusView != null && hadFocus && !focusView.hasFocus()) { 1835 focusView.requestFocus(); 1836 } 1837 appendVisibleItems(); 1838 prependVisibleItems(); 1839 removeInvisibleViewsAtFront(); 1840 removeInvisibleViewsAtEnd(); 1841 } while (mGrid.getFirstVisibleIndex() != oldFirstVisible || 1842 mGrid.getLastVisibleIndex() != oldLastVisible); 1843 } 1844 1845 if (scrollToFocus) { 1846 scrollDirectionPrimary(-delta); 1847 scrollDirectionSecondary(-deltaSecondary); 1848 } 1849 appendVisibleItems(); 1850 prependVisibleItems(); 1851 removeInvisibleViewsAtFront(); 1852 removeInvisibleViewsAtEnd(); 1853 1854 if (DEBUG) { 1855 StringWriter sw = new StringWriter(); 1856 PrintWriter pw = new PrintWriter(sw); 1857 mGrid.debugPrint(pw); 1858 Log.d(getTag(), sw.toString()); 1859 } 1860 1861 if (mRowSecondarySizeRefresh) { 1862 mRowSecondarySizeRefresh = false; 1863 } else { 1864 updateRowSecondarySizeRefresh(); 1865 } 1866 1867 // For fastRelayout, only dispatch event when focus position changes. 1868 if (mInFastRelayout && mFocusPosition != savedFocusPos) { 1869 dispatchChildSelected(); 1870 } else if (!mInFastRelayout && mInLayoutSearchFocus) { 1871 // For full layout we dispatchChildSelected() in createItem() unless searched all 1872 // children and found none is focusable then dispatchChildSelected() here. 1873 dispatchChildSelected(); 1874 } 1875 1876 mInLayout = false; 1877 leaveContext(); 1878 if (DEBUG) Log.v(getTag(), "layoutChildren end"); 1879 } 1880 1881 private void offsetChildrenSecondary(int increment) { 1882 final int childCount = getChildCount(); 1883 if (mOrientation == HORIZONTAL) { 1884 for (int i = 0; i < childCount; i++) { 1885 getChildAt(i).offsetTopAndBottom(increment); 1886 } 1887 } else { 1888 for (int i = 0; i < childCount; i++) { 1889 getChildAt(i).offsetLeftAndRight(increment); 1890 } 1891 } 1892 } 1893 1894 private void offsetChildrenPrimary(int increment) { 1895 final int childCount = getChildCount(); 1896 if (mOrientation == VERTICAL) { 1897 for (int i = 0; i < childCount; i++) { 1898 getChildAt(i).offsetTopAndBottom(increment); 1899 } 1900 } else { 1901 for (int i = 0; i < childCount; i++) { 1902 getChildAt(i).offsetLeftAndRight(increment); 1903 } 1904 } 1905 } 1906 1907 @Override 1908 public int scrollHorizontallyBy(int dx, Recycler recycler, RecyclerView.State state) { 1909 if (DEBUG) Log.v(getTag(), "scrollHorizontallyBy " + dx); 1910 if (!mLayoutEnabled || !hasDoneFirstLayout()) { 1911 return 0; 1912 } 1913 saveContext(recycler, state); 1914 mInScroll = true; 1915 int result; 1916 if (mOrientation == HORIZONTAL) { 1917 result = scrollDirectionPrimary(dx); 1918 } else { 1919 result = scrollDirectionSecondary(dx); 1920 } 1921 leaveContext(); 1922 mInScroll = false; 1923 return result; 1924 } 1925 1926 @Override 1927 public int scrollVerticallyBy(int dy, Recycler recycler, RecyclerView.State state) { 1928 if (DEBUG) Log.v(getTag(), "scrollVerticallyBy " + dy); 1929 if (!mLayoutEnabled || !hasDoneFirstLayout()) { 1930 return 0; 1931 } 1932 mInScroll = true; 1933 saveContext(recycler, state); 1934 int result; 1935 if (mOrientation == VERTICAL) { 1936 result = scrollDirectionPrimary(dy); 1937 } else { 1938 result = scrollDirectionSecondary(dy); 1939 } 1940 leaveContext(); 1941 mInScroll = false; 1942 return result; 1943 } 1944 1945 // scroll in main direction may add/prune views 1946 private int scrollDirectionPrimary(int da) { 1947 if (TRACE) TraceHelper.beginSection("scrollPrimary"); 1948 boolean isMaxUnknown = false, isMinUnknown = false; 1949 int minScroll = 0, maxScroll = 0; 1950 if (da > 0) { 1951 isMaxUnknown = mWindowAlignment.mainAxis().isMaxUnknown(); 1952 if (!isMaxUnknown) { 1953 maxScroll = mWindowAlignment.mainAxis().getMaxScroll(); 1954 if (mScrollOffsetPrimary + da > maxScroll) { 1955 da = maxScroll - mScrollOffsetPrimary; 1956 } 1957 } 1958 } else if (da < 0) { 1959 isMinUnknown = mWindowAlignment.mainAxis().isMinUnknown(); 1960 if (!isMinUnknown) { 1961 minScroll = mWindowAlignment.mainAxis().getMinScroll(); 1962 if (mScrollOffsetPrimary + da < minScroll) { 1963 da = minScroll - mScrollOffsetPrimary; 1964 } 1965 } 1966 } 1967 if (da == 0) { 1968 if (TRACE) TraceHelper.endSection(); 1969 return 0; 1970 } 1971 offsetChildrenPrimary(-da); 1972 mScrollOffsetPrimary += da; 1973 if (mInLayout) { 1974 if (TRACE) TraceHelper.endSection(); 1975 return da; 1976 } 1977 1978 int childCount = getChildCount(); 1979 boolean updated; 1980 1981 if (mReverseFlowPrimary ? da > 0 : da < 0) { 1982 prependVisibleItems(); 1983 } else { 1984 appendVisibleItems(); 1985 } 1986 updated = getChildCount() > childCount; 1987 childCount = getChildCount(); 1988 1989 if (TRACE) TraceHelper.beginSection("remove"); 1990 if (mReverseFlowPrimary ? da > 0 : da < 0) { 1991 removeInvisibleViewsAtEnd(); 1992 } else { 1993 removeInvisibleViewsAtFront(); 1994 } 1995 if (TRACE) TraceHelper.endSection(); 1996 updated |= getChildCount() < childCount; 1997 if (updated) { 1998 updateRowSecondarySizeRefresh(); 1999 } 2000 2001 mBaseGridView.invalidate(); 2002 if (TRACE) TraceHelper.endSection(); 2003 return da; 2004 } 2005 2006 // scroll in second direction will not add/prune views 2007 private int scrollDirectionSecondary(int dy) { 2008 if (dy == 0) { 2009 return 0; 2010 } 2011 offsetChildrenSecondary(-dy); 2012 mScrollOffsetSecondary += dy; 2013 mBaseGridView.invalidate(); 2014 return dy; 2015 } 2016 2017 private void updateScrollMax() { 2018 int highVisiblePos = (!mReverseFlowPrimary) ? mGrid.getLastVisibleIndex() 2019 : mGrid.getFirstVisibleIndex(); 2020 int highMaxPos = (!mReverseFlowPrimary) ? mState.getItemCount() - 1 : 0; 2021 if (highVisiblePos < 0) { 2022 return; 2023 } 2024 final boolean highAvailable = highVisiblePos == highMaxPos; 2025 final boolean maxUnknown = mWindowAlignment.mainAxis().isMaxUnknown(); 2026 if (!highAvailable && maxUnknown) { 2027 return; 2028 } 2029 int maxEdge = mGrid.findRowMax(true, sTwoInts) + mScrollOffsetPrimary; 2030 int rowIndex = sTwoInts[0]; 2031 int pos = sTwoInts[1]; 2032 int savedMaxEdge = mWindowAlignment.mainAxis().getMaxEdge(); 2033 mWindowAlignment.mainAxis().setMaxEdge(maxEdge); 2034 int maxScroll = getPrimarySystemScrollPositionOfChildMax(findViewByPosition(pos)); 2035 mWindowAlignment.mainAxis().setMaxEdge(savedMaxEdge); 2036 2037 if (highAvailable) { 2038 mWindowAlignment.mainAxis().setMaxEdge(maxEdge); 2039 mWindowAlignment.mainAxis().setMaxScroll(maxScroll); 2040 if (DEBUG) Log.v(getTag(), "updating scroll maxEdge to " + maxEdge + 2041 " scrollMax to " + maxScroll); 2042 } else { 2043 mWindowAlignment.mainAxis().invalidateScrollMax(); 2044 if (DEBUG) Log.v(getTag(), "Invalidate scrollMax since it should be " 2045 + "greater than " + maxScroll); 2046 } 2047 } 2048 2049 private void updateScrollMin() { 2050 int lowVisiblePos = (!mReverseFlowPrimary) ? mGrid.getFirstVisibleIndex() 2051 : mGrid.getLastVisibleIndex(); 2052 int lowMinPos = (!mReverseFlowPrimary) ? 0 : mState.getItemCount() - 1; 2053 if (lowVisiblePos < 0) { 2054 return; 2055 } 2056 final boolean lowAvailable = lowVisiblePos == lowMinPos; 2057 final boolean minUnknown = mWindowAlignment.mainAxis().isMinUnknown(); 2058 if (!lowAvailable && minUnknown) { 2059 return; 2060 } 2061 int minEdge = mGrid.findRowMin(false, sTwoInts) + mScrollOffsetPrimary; 2062 int rowIndex = sTwoInts[0]; 2063 int pos = sTwoInts[1]; 2064 int savedMinEdge = mWindowAlignment.mainAxis().getMinEdge(); 2065 mWindowAlignment.mainAxis().setMinEdge(minEdge); 2066 int minScroll = getPrimarySystemScrollPosition(findViewByPosition(pos)); 2067 mWindowAlignment.mainAxis().setMinEdge(savedMinEdge); 2068 2069 if (lowAvailable) { 2070 mWindowAlignment.mainAxis().setMinEdge(minEdge); 2071 mWindowAlignment.mainAxis().setMinScroll(minScroll); 2072 if (DEBUG) Log.v(getTag(), "updating scroll minEdge to " + minEdge + 2073 " scrollMin to " + minScroll); 2074 } else { 2075 mWindowAlignment.mainAxis().invalidateScrollMin(); 2076 if (DEBUG) Log.v(getTag(), "Invalidate scrollMin, since it should be " 2077 + "less than " + minScroll); 2078 } 2079 } 2080 2081 private void updateScrollSecondAxis() { 2082 mWindowAlignment.secondAxis().setMinEdge(0); 2083 mWindowAlignment.secondAxis().setMaxEdge(getSizeSecondary()); 2084 } 2085 2086 private void initScrollController() { 2087 mWindowAlignment.reset(); 2088 mWindowAlignment.horizontal.setSize(getWidth()); 2089 mWindowAlignment.vertical.setSize(getHeight()); 2090 mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight()); 2091 mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom()); 2092 mSizePrimary = mWindowAlignment.mainAxis().getSize(); 2093 mScrollOffsetPrimary = -mWindowAlignment.mainAxis().getPaddingLow(); 2094 mScrollOffsetSecondary = -mWindowAlignment.secondAxis().getPaddingLow(); 2095 2096 if (DEBUG) { 2097 Log.v(getTag(), "initScrollController mSizePrimary " + mSizePrimary 2098 + " mWindowAlignment " + mWindowAlignment 2099 + " mScrollOffsetPrimary " + mScrollOffsetPrimary); 2100 } 2101 } 2102 2103 private void updateScrollController() { 2104 // mScrollOffsetPrimary and mScrollOffsetSecondary includes the padding. 2105 // e.g. when topPadding is 16 for horizontal grid view, the initial 2106 // mScrollOffsetSecondary is -16. fastRelayout() put views based on offsets(not padding), 2107 // when padding changes to 20, we also need update mScrollOffsetSecondary to -20 before 2108 // fastRelayout() is performed 2109 int paddingPrimaryDiff, paddingSecondaryDiff; 2110 if (mOrientation == HORIZONTAL) { 2111 paddingPrimaryDiff = getPaddingLeft() - mWindowAlignment.horizontal.getPaddingLow(); 2112 paddingSecondaryDiff = getPaddingTop() - mWindowAlignment.vertical.getPaddingLow(); 2113 } else { 2114 paddingPrimaryDiff = getPaddingTop() - mWindowAlignment.vertical.getPaddingLow(); 2115 paddingSecondaryDiff = getPaddingLeft() - mWindowAlignment.horizontal.getPaddingLow(); 2116 } 2117 mScrollOffsetPrimary -= paddingPrimaryDiff; 2118 mScrollOffsetSecondary -= paddingSecondaryDiff; 2119 2120 mWindowAlignment.horizontal.setSize(getWidth()); 2121 mWindowAlignment.vertical.setSize(getHeight()); 2122 mWindowAlignment.horizontal.setPadding(getPaddingLeft(), getPaddingRight()); 2123 mWindowAlignment.vertical.setPadding(getPaddingTop(), getPaddingBottom()); 2124 mSizePrimary = mWindowAlignment.mainAxis().getSize(); 2125 2126 if (DEBUG) { 2127 Log.v(getTag(), "updateScrollController mSizePrimary " + mSizePrimary 2128 + " mWindowAlignment " + mWindowAlignment 2129 + " mScrollOffsetPrimary " + mScrollOffsetPrimary); 2130 } 2131 } 2132 2133 public void setSelection(RecyclerView parent, int position, 2134 int primaryScrollExtra) { 2135 setSelection(parent, position, 0, false, primaryScrollExtra); 2136 } 2137 2138 public void setSelectionSmooth(RecyclerView parent, int position) { 2139 setSelection(parent, position, 0, true, 0); 2140 } 2141 2142 public void setSelectionWithSub(RecyclerView parent, int position, int subposition, 2143 int primaryScrollExtra) { 2144 setSelection(parent, position, subposition, false, primaryScrollExtra); 2145 } 2146 2147 public void setSelectionSmoothWithSub(RecyclerView parent, int position, int subposition) { 2148 setSelection(parent, position, subposition, true, 0); 2149 } 2150 2151 public int getSelection() { 2152 return mFocusPosition; 2153 } 2154 2155 public int getSubSelection() { 2156 return mSubFocusPosition; 2157 } 2158 2159 public void setSelection(RecyclerView parent, int position, int subposition, boolean smooth, 2160 int primaryScrollExtra) { 2161 if (mFocusPosition != position && position != NO_POSITION 2162 || subposition != mSubFocusPosition || primaryScrollExtra != mPrimaryScrollExtra) { 2163 scrollToSelection(parent, position, subposition, smooth, primaryScrollExtra); 2164 } 2165 } 2166 2167 private void scrollToSelection(RecyclerView parent, int position, int subposition, 2168 boolean smooth, int primaryScrollExtra) { 2169 if (TRACE) TraceHelper.beginSection("scrollToSelection"); 2170 mPrimaryScrollExtra = primaryScrollExtra; 2171 View view = findViewByPosition(position); 2172 if (view != null) { 2173 mInSelection = true; 2174 scrollToView(view, smooth); 2175 mInSelection = false; 2176 } else { 2177 mFocusPosition = position; 2178 mSubFocusPosition = subposition; 2179 mFocusPositionOffset = Integer.MIN_VALUE; 2180 if (!mLayoutEnabled) { 2181 return; 2182 } 2183 if (smooth) { 2184 if (!hasDoneFirstLayout()) { 2185 Log.w(getTag(), "setSelectionSmooth should " + 2186 "not be called before first layout pass"); 2187 return; 2188 } 2189 startPositionSmoothScroller(position); 2190 } else { 2191 mForceFullLayout = true; 2192 parent.requestLayout(); 2193 } 2194 } 2195 if (TRACE) TraceHelper.endSection(); 2196 } 2197 2198 void startPositionSmoothScroller(int position) { 2199 LinearSmoothScroller linearSmoothScroller = new GridLinearSmoothScroller() { 2200 @Override 2201 public PointF computeScrollVectorForPosition(int targetPosition) { 2202 if (getChildCount() == 0) { 2203 return null; 2204 } 2205 final int firstChildPos = getPosition(getChildAt(0)); 2206 // TODO We should be able to deduce direction from bounds of current and target 2207 // focus, rather than making assumptions about positions and directionality 2208 final boolean isStart = mReverseFlowPrimary ? targetPosition > firstChildPos 2209 : targetPosition < firstChildPos; 2210 final int direction = isStart ? -1 : 1; 2211 if (mOrientation == HORIZONTAL) { 2212 return new PointF(direction, 0); 2213 } else { 2214 return new PointF(0, direction); 2215 } 2216 } 2217 2218 }; 2219 linearSmoothScroller.setTargetPosition(position); 2220 startSmoothScroll(linearSmoothScroller); 2221 } 2222 2223 private void processPendingMovement(boolean forward) { 2224 if (forward ? hasCreatedLastItem() : hasCreatedFirstItem()) { 2225 return; 2226 } 2227 if (mPendingMoveSmoothScroller == null) { 2228 // Stop existing scroller and create a new PendingMoveSmoothScroller. 2229 mBaseGridView.stopScroll(); 2230 PendingMoveSmoothScroller linearSmoothScroller = new PendingMoveSmoothScroller( 2231 forward ? 1 : -1, mNumRows > 1); 2232 mFocusPositionOffset = 0; 2233 startSmoothScroll(linearSmoothScroller); 2234 if (linearSmoothScroller.isRunning()) { 2235 mPendingMoveSmoothScroller = linearSmoothScroller; 2236 } 2237 } else { 2238 if (forward) { 2239 mPendingMoveSmoothScroller.increasePendingMoves(); 2240 } else { 2241 mPendingMoveSmoothScroller.decreasePendingMoves(); 2242 } 2243 } 2244 } 2245 2246 @Override 2247 public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) { 2248 if (DEBUG) Log.v(getTag(), "onItemsAdded positionStart " 2249 + positionStart + " itemCount " + itemCount); 2250 if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) { 2251 int pos = mFocusPosition + mFocusPositionOffset; 2252 if (positionStart <= pos) { 2253 mFocusPositionOffset += itemCount; 2254 } 2255 } 2256 mChildrenStates.clear(); 2257 } 2258 2259 @Override 2260 public void onItemsChanged(RecyclerView recyclerView) { 2261 if (DEBUG) Log.v(getTag(), "onItemsChanged"); 2262 mFocusPositionOffset = 0; 2263 mChildrenStates.clear(); 2264 } 2265 2266 @Override 2267 public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) { 2268 if (DEBUG) Log.v(getTag(), "onItemsRemoved positionStart " 2269 + positionStart + " itemCount " + itemCount); 2270 if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) { 2271 int pos = mFocusPosition + mFocusPositionOffset; 2272 if (positionStart <= pos) { 2273 if (positionStart + itemCount > pos) { 2274 // stop updating offset after the focus item was removed 2275 mFocusPositionOffset = Integer.MIN_VALUE; 2276 } else { 2277 mFocusPositionOffset -= itemCount; 2278 } 2279 } 2280 } 2281 mChildrenStates.clear(); 2282 } 2283 2284 @Override 2285 public void onItemsMoved(RecyclerView recyclerView, int fromPosition, int toPosition, 2286 int itemCount) { 2287 if (DEBUG) Log.v(getTag(), "onItemsMoved fromPosition " 2288 + fromPosition + " toPosition " + toPosition); 2289 if (mFocusPosition != NO_POSITION && mFocusPositionOffset != Integer.MIN_VALUE) { 2290 int pos = mFocusPosition + mFocusPositionOffset; 2291 if (fromPosition <= pos && pos < fromPosition + itemCount) { 2292 // moved items include focused position 2293 mFocusPositionOffset += toPosition - fromPosition; 2294 } else if (fromPosition < pos && toPosition > pos - itemCount) { 2295 // move items before focus position to after focused position 2296 mFocusPositionOffset -= itemCount; 2297 } else if (fromPosition > pos && toPosition < pos) { 2298 // move items after focus position to before focused position 2299 mFocusPositionOffset += itemCount; 2300 } 2301 } 2302 mChildrenStates.clear(); 2303 } 2304 2305 @Override 2306 public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount) { 2307 if (DEBUG) Log.v(getTag(), "onItemsUpdated positionStart " 2308 + positionStart + " itemCount " + itemCount); 2309 for (int i = positionStart, end = positionStart + itemCount; i < end; i++) { 2310 mChildrenStates.remove(i); 2311 } 2312 } 2313 2314 @Override 2315 public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) { 2316 if (mFocusSearchDisabled) { 2317 return true; 2318 } 2319 if (getPositionByView(child) == NO_POSITION) { 2320 // This shouldn't happen, but in case it does be sure not to attempt a 2321 // scroll to a view whose item has been removed. 2322 return true; 2323 } 2324 if (!mInLayout && !mInSelection && !mInScroll) { 2325 scrollToView(child, focused, true); 2326 } 2327 return true; 2328 } 2329 2330 @Override 2331 public boolean requestChildRectangleOnScreen(RecyclerView parent, View view, Rect rect, 2332 boolean immediate) { 2333 if (DEBUG) Log.v(getTag(), "requestChildRectangleOnScreen " + view + " " + rect); 2334 return false; 2335 } 2336 2337 int getScrollOffsetX() { 2338 return mOrientation == HORIZONTAL ? mScrollOffsetPrimary : mScrollOffsetSecondary; 2339 } 2340 2341 int getScrollOffsetY() { 2342 return mOrientation == HORIZONTAL ? mScrollOffsetSecondary : mScrollOffsetPrimary; 2343 } 2344 2345 public void getViewSelectedOffsets(View view, int[] offsets) { 2346 if (mOrientation == HORIZONTAL) { 2347 offsets[0] = getPrimarySystemScrollPosition(view) - mScrollOffsetPrimary; 2348 offsets[1] = getSecondarySystemScrollPosition(view) - mScrollOffsetSecondary; 2349 } else { 2350 offsets[1] = getPrimarySystemScrollPosition(view) - mScrollOffsetPrimary; 2351 offsets[0] = getSecondarySystemScrollPosition(view) - mScrollOffsetSecondary; 2352 } 2353 } 2354 2355 private int getPrimarySystemScrollPosition(View view) { 2356 final int viewCenterPrimary = mScrollOffsetPrimary + getViewCenter(view); 2357 final int viewMin = getViewMin(view); 2358 final int viewMax = getViewMax(view); 2359 // TODO: change to use State object in onRequestChildFocus() 2360 boolean isMin, isMax; 2361 if (!mReverseFlowPrimary) { 2362 isMin = mGrid.getFirstVisibleIndex() == 0; 2363 isMax = mGrid.getLastVisibleIndex() == (mState == null ? 2364 getItemCount() : mState.getItemCount()) - 1; 2365 } else { 2366 isMax = mGrid.getFirstVisibleIndex() == 0; 2367 isMin = mGrid.getLastVisibleIndex() == (mState == null ? 2368 getItemCount() : mState.getItemCount()) - 1; 2369 } 2370 for (int i = getChildCount() - 1; (isMin || isMax) && i >= 0; i--) { 2371 View v = getChildAt(i); 2372 if (v == view || v == null) { 2373 continue; 2374 } 2375 if (isMin && getViewMin(v) < viewMin) { 2376 isMin = false; 2377 } 2378 if (isMax && getViewMax(v) > viewMax) { 2379 isMax = false; 2380 } 2381 } 2382 return mWindowAlignment.mainAxis().getSystemScrollPos(viewCenterPrimary, isMin, isMax); 2383 } 2384 2385 private int getPrimarySystemScrollPositionOfChildMax(View view) { 2386 int scrollPosition = getPrimarySystemScrollPosition(view); 2387 final LayoutParams lp = (LayoutParams) view.getLayoutParams(); 2388 int[] multipleAligns = lp.getAlignMultiple(); 2389 if (multipleAligns != null && multipleAligns.length > 0) { 2390 scrollPosition += multipleAligns[multipleAligns.length - 1] - multipleAligns[0]; 2391 } 2392 return scrollPosition; 2393 } 2394 2395 /** 2396 * Get adjusted primary position for a given childView (if there is multiple ItemAlignment defined 2397 * on the view). 2398 */ 2399 private int getAdjustedPrimaryScrollPosition(int scrollPrimary, View view, View childView) { 2400 int subindex = getSubPositionByView(view, childView); 2401 if (subindex != 0) { 2402 final LayoutParams lp = (LayoutParams) view.getLayoutParams(); 2403 scrollPrimary += lp.getAlignMultiple()[subindex] - lp.getAlignMultiple()[0]; 2404 } 2405 return scrollPrimary; 2406 } 2407 2408 private int getSecondarySystemScrollPosition(View view) { 2409 int viewCenterSecondary = mScrollOffsetSecondary + getViewCenterSecondary(view); 2410 int pos = getPositionByView(view); 2411 Grid.Location location = mGrid.getLocation(pos); 2412 final int row = location.row; 2413 final boolean isMin, isMax; 2414 if (!mReverseFlowSecondary) { 2415 isMin = row == 0; 2416 isMax = row == mGrid.getNumRows() - 1; 2417 } else { 2418 isMax = row == 0; 2419 isMin = row == mGrid.getNumRows() - 1; 2420 } 2421 return mWindowAlignment.secondAxis().getSystemScrollPos(viewCenterSecondary, isMin, isMax); 2422 } 2423 2424 /** 2425 * Scroll to a given child view and change mFocusPosition. 2426 */ 2427 private void scrollToView(View view, boolean smooth) { 2428 scrollToView(view, view == null ? null : view.findFocus(), smooth); 2429 } 2430 2431 /** 2432 * Scroll to a given child view and change mFocusPosition. 2433 */ 2434 private void scrollToView(View view, View childView, boolean smooth) { 2435 int newFocusPosition = getPositionByView(view); 2436 int newSubFocusPosition = getSubPositionByView(view, childView); 2437 if (newFocusPosition != mFocusPosition || newSubFocusPosition != mSubFocusPosition) { 2438 mFocusPosition = newFocusPosition; 2439 mSubFocusPosition = newSubFocusPosition; 2440 mFocusPositionOffset = 0; 2441 if (!mInLayout) { 2442 dispatchChildSelected(); 2443 } 2444 if (mBaseGridView.isChildrenDrawingOrderEnabledInternal()) { 2445 mBaseGridView.invalidate(); 2446 } 2447 } 2448 if (view == null) { 2449 return; 2450 } 2451 if (!view.hasFocus() && mBaseGridView.hasFocus()) { 2452 // transfer focus to the child if it does not have focus yet (e.g. triggered 2453 // by setSelection()) 2454 view.requestFocus(); 2455 } 2456 if (!mScrollEnabled && smooth) { 2457 return; 2458 } 2459 if (getScrollPosition(view, childView, sTwoInts)) { 2460 scrollGrid(sTwoInts[0], sTwoInts[1], smooth); 2461 } 2462 } 2463 2464 private boolean getScrollPosition(View view, View childView, int[] deltas) { 2465 switch (mFocusScrollStrategy) { 2466 case BaseGridView.FOCUS_SCROLL_ALIGNED: 2467 default: 2468 return getAlignedPosition(view, childView, deltas); 2469 case BaseGridView.FOCUS_SCROLL_ITEM: 2470 case BaseGridView.FOCUS_SCROLL_PAGE: 2471 return getNoneAlignedPosition(view, deltas); 2472 } 2473 } 2474 2475 private boolean getNoneAlignedPosition(View view, int[] deltas) { 2476 int pos = getPositionByView(view); 2477 int viewMin = getViewMin(view); 2478 int viewMax = getViewMax(view); 2479 // we either align "firstView" to left/top padding edge 2480 // or align "lastView" to right/bottom padding edge 2481 View firstView = null; 2482 View lastView = null; 2483 int paddingLow = mWindowAlignment.mainAxis().getPaddingLow(); 2484 int clientSize = mWindowAlignment.mainAxis().getClientSize(); 2485 final int row = mGrid.getRowIndex(pos); 2486 if (viewMin < paddingLow) { 2487 // view enters low padding area: 2488 firstView = view; 2489 if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) { 2490 // scroll one "page" left/top, 2491 // align first visible item of the "page" at the low padding edge. 2492 while (prependOneColumnVisibleItems()) { 2493 CircularIntArray positions = 2494 mGrid.getItemPositionsInRows(mGrid.getFirstVisibleIndex(), pos)[row]; 2495 firstView = findViewByPosition(positions.get(0)); 2496 if (viewMax - getViewMin(firstView) > clientSize) { 2497 if (positions.size() > 2) { 2498 firstView = findViewByPosition(positions.get(2)); 2499 } 2500 break; 2501 } 2502 } 2503 } 2504 } else if (viewMax > clientSize + paddingLow) { 2505 // view enters high padding area: 2506 if (mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_PAGE) { 2507 // scroll whole one page right/bottom, align view at the low padding edge. 2508 firstView = view; 2509 do { 2510 CircularIntArray positions = 2511 mGrid.getItemPositionsInRows(pos, mGrid.getLastVisibleIndex())[row]; 2512 lastView = findViewByPosition(positions.get(positions.size() - 1)); 2513 if (getViewMax(lastView) - viewMin > clientSize) { 2514 lastView = null; 2515 break; 2516 } 2517 } while (appendOneColumnVisibleItems()); 2518 if (lastView != null) { 2519 // however if we reached end, we should align last view. 2520 firstView = null; 2521 } 2522 } else { 2523 lastView = view; 2524 } 2525 } 2526 int scrollPrimary = 0; 2527 int scrollSecondary = 0; 2528 if (firstView != null) { 2529 scrollPrimary = getViewMin(firstView) - paddingLow; 2530 } else if (lastView != null) { 2531 scrollPrimary = getViewMax(lastView) - (paddingLow + clientSize); 2532 } 2533 View secondaryAlignedView; 2534 if (firstView != null) { 2535 secondaryAlignedView = firstView; 2536 } else if (lastView != null) { 2537 secondaryAlignedView = lastView; 2538 } else { 2539 secondaryAlignedView = view; 2540 } 2541 scrollSecondary = getSecondarySystemScrollPosition(secondaryAlignedView); 2542 scrollSecondary -= mScrollOffsetSecondary; 2543 if (scrollPrimary != 0 || scrollSecondary != 0) { 2544 deltas[0] = scrollPrimary; 2545 deltas[1] = scrollSecondary; 2546 return true; 2547 } 2548 return false; 2549 } 2550 2551 private boolean getAlignedPosition(View view, View childView, int[] deltas) { 2552 int scrollPrimary = getPrimarySystemScrollPosition(view); 2553 if (childView != null) { 2554 scrollPrimary = getAdjustedPrimaryScrollPosition(scrollPrimary, view, childView); 2555 } 2556 int scrollSecondary = getSecondarySystemScrollPosition(view); 2557 if (DEBUG) { 2558 Log.v(getTag(), "getAlignedPosition " + scrollPrimary + " " + scrollSecondary 2559 + " " + mPrimaryScrollExtra + " " + mWindowAlignment); 2560 Log.v(getTag(), "getAlignedPosition " + mScrollOffsetPrimary + " " + mScrollOffsetSecondary); 2561 } 2562 scrollPrimary -= mScrollOffsetPrimary; 2563 scrollSecondary -= mScrollOffsetSecondary; 2564 scrollPrimary += mPrimaryScrollExtra; 2565 if (scrollPrimary != 0 || scrollSecondary != 0) { 2566 deltas[0] = scrollPrimary; 2567 deltas[1] = scrollSecondary; 2568 return true; 2569 } 2570 return false; 2571 } 2572 2573 private void scrollGrid(int scrollPrimary, int scrollSecondary, boolean smooth) { 2574 if (mInLayout) { 2575 scrollDirectionPrimary(scrollPrimary); 2576 scrollDirectionSecondary(scrollSecondary); 2577 } else { 2578 int scrollX; 2579 int scrollY; 2580 if (mOrientation == HORIZONTAL) { 2581 scrollX = scrollPrimary; 2582 scrollY = scrollSecondary; 2583 } else { 2584 scrollX = scrollSecondary; 2585 scrollY = scrollPrimary; 2586 } 2587 if (smooth) { 2588 mBaseGridView.smoothScrollBy(scrollX, scrollY); 2589 } else { 2590 mBaseGridView.scrollBy(scrollX, scrollY); 2591 } 2592 } 2593 } 2594 2595 public void setPruneChild(boolean pruneChild) { 2596 if (mPruneChild != pruneChild) { 2597 mPruneChild = pruneChild; 2598 if (mPruneChild) { 2599 requestLayout(); 2600 } 2601 } 2602 } 2603 2604 public boolean getPruneChild() { 2605 return mPruneChild; 2606 } 2607 2608 public void setScrollEnabled(boolean scrollEnabled) { 2609 if (mScrollEnabled != scrollEnabled) { 2610 mScrollEnabled = scrollEnabled; 2611 if (mScrollEnabled && mFocusScrollStrategy == BaseGridView.FOCUS_SCROLL_ALIGNED 2612 && mFocusPosition != NO_POSITION) { 2613 scrollToSelection(mBaseGridView, mFocusPosition, mSubFocusPosition, 2614 true, mPrimaryScrollExtra); 2615 } 2616 } 2617 } 2618 2619 public boolean isScrollEnabled() { 2620 return mScrollEnabled; 2621 } 2622 2623 private int findImmediateChildIndex(View view) { 2624 while (view != null && view != mBaseGridView) { 2625 int index = mBaseGridView.indexOfChild(view); 2626 if (index >= 0) { 2627 return index; 2628 } 2629 view = (View) view.getParent(); 2630 } 2631 return NO_POSITION; 2632 } 2633 2634 void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 2635 if (gainFocus) { 2636 // if gridview.requestFocus() is called, select first focusable child. 2637 for (int i = mFocusPosition; ;i++) { 2638 View view = findViewByPosition(i); 2639 if (view == null) { 2640 break; 2641 } 2642 if (view.getVisibility() == View.VISIBLE && view.hasFocusable()) { 2643 view.requestFocus(); 2644 break; 2645 } 2646 } 2647 } 2648 } 2649 2650 void setFocusSearchDisabled(boolean disabled) { 2651 mFocusSearchDisabled = disabled; 2652 } 2653 2654 boolean isFocusSearchDisabled() { 2655 return mFocusSearchDisabled; 2656 } 2657 2658 @Override 2659 public View onInterceptFocusSearch(View focused, int direction) { 2660 if (mFocusSearchDisabled) { 2661 return focused; 2662 } 2663 return null; 2664 } 2665 2666 boolean hasPreviousViewInSameRow(int pos) { 2667 if (mGrid == null || pos == NO_POSITION || mGrid.getFirstVisibleIndex() < 0) { 2668 return false; 2669 } 2670 if (mGrid.getFirstVisibleIndex() > 0) { 2671 return true; 2672 } 2673 final int focusedRow = mGrid.getLocation(pos).row; 2674 for (int i = getChildCount() - 1; i >= 0; i--) { 2675 int position = getPositionByIndex(i); 2676 Grid.Location loc = mGrid.getLocation(position); 2677 if (loc != null && loc.row == focusedRow) { 2678 if (position < pos) { 2679 return true; 2680 } 2681 } 2682 } 2683 return false; 2684 } 2685 2686 @Override 2687 public boolean onAddFocusables(RecyclerView recyclerView, 2688 ArrayList<View> views, int direction, int focusableMode) { 2689 if (mFocusSearchDisabled) { 2690 return true; 2691 } 2692 // If this viewgroup or one of its children currently has focus then we 2693 // consider our children for focus searching in main direction on the same row. 2694 // If this viewgroup has no focus and using focus align, we want the system 2695 // to ignore our children and pass focus to the viewgroup, which will pass 2696 // focus on to its children appropriately. 2697 // If this viewgroup has no focus and not using focus align, we want to 2698 // consider the child that does not overlap with padding area. 2699 if (recyclerView.hasFocus()) { 2700 final int movement = getMovement(direction); 2701 if (movement != PREV_ITEM && movement != NEXT_ITEM) { 2702 // Move on secondary direction uses default addFocusables(). 2703 return false; 2704 } 2705 if (mPendingMoveSmoothScroller != null) { 2706 // don't find next focusable if has pending movement. 2707 return true; 2708 } 2709 final View focused = recyclerView.findFocus(); 2710 final int focusedPos = getPositionByIndex(findImmediateChildIndex(focused)); 2711 // Add focusables of focused item. 2712 if (focusedPos != NO_POSITION) { 2713 findViewByPosition(focusedPos).addFocusables(views, direction, focusableMode); 2714 } 2715 final int focusedRow = mGrid != null && focusedPos != NO_POSITION ? 2716 mGrid.getLocation(focusedPos).row : NO_POSITION; 2717 // Add focusables of next neighbor of same row on the focus search direction. 2718 if (mGrid != null) { 2719 final int focusableCount = views.size(); 2720 for (int i = 0, count = getChildCount(); i < count; i++) { 2721 int index = movement == NEXT_ITEM ? i : count - 1 - i; 2722 final View child = getChildAt(index); 2723 if (child.getVisibility() != View.VISIBLE || !child.hasFocusable()) { 2724 continue; 2725 } 2726 int position = getPositionByIndex(index); 2727 Grid.Location loc = mGrid.getLocation(position); 2728 if (focusedRow == NO_POSITION || (loc != null && loc.row == focusedRow)) { 2729 if (focusedPos == NO_POSITION || 2730 (movement == NEXT_ITEM && position > focusedPos) 2731 || (movement == PREV_ITEM && position < focusedPos)) { 2732 child.addFocusables(views, direction, focusableMode); 2733 if (views.size() > focusableCount) { 2734 break; 2735 } 2736 } 2737 } 2738 } 2739 } 2740 } else { 2741 if (mFocusScrollStrategy != BaseGridView.FOCUS_SCROLL_ALIGNED) { 2742 // adding views not overlapping padding area to avoid scrolling in gaining focus 2743 int left = mWindowAlignment.mainAxis().getPaddingLow(); 2744 int right = mWindowAlignment.mainAxis().getClientSize() + left; 2745 int focusableCount = views.size(); 2746 for (int i = 0, count = getChildCount(); i < count; i++) { 2747 View child = getChildAt(i); 2748 if (child.getVisibility() == View.VISIBLE) { 2749 if (getViewMin(child) >= left && getViewMax(child) <= right) { 2750 child.addFocusables(views, direction, focusableMode); 2751 } 2752 } 2753 } 2754 // if we cannot find any, then just add all children. 2755 if (views.size() == focusableCount) { 2756 for (int i = 0, count = getChildCount(); i < count; i++) { 2757 View child = getChildAt(i); 2758 if (child.getVisibility() == View.VISIBLE) { 2759 child.addFocusables(views, direction, focusableMode); 2760 } 2761 } 2762 if (views.size() != focusableCount) { 2763 return true; 2764 } 2765 } else { 2766 return true; 2767 } 2768 // if still cannot find any, fall through and add itself 2769 } 2770 if (recyclerView.isFocusable()) { 2771 views.add(recyclerView); 2772 } 2773 } 2774 return true; 2775 } 2776 2777 private boolean hasCreatedLastItem() { 2778 int count = mState.getItemCount(); 2779 return count == 0 || findViewByPosition(count - 1) != null; 2780 } 2781 2782 private boolean hasCreatedFirstItem() { 2783 int count = mState.getItemCount(); 2784 return count == 0 || findViewByPosition(0) != null; 2785 } 2786 2787 boolean canScrollTo(View view) { 2788 return view.getVisibility() == View.VISIBLE && (!hasFocus() || view.hasFocusable()); 2789 } 2790 2791 @Override 2792 public View onFocusSearchFailed(View focused, int direction, Recycler recycler, 2793 RecyclerView.State state) { 2794 if (DEBUG) Log.v(getTag(), "onFocusSearchFailed direction " + direction); 2795 2796 View view = null; 2797 int movement = getMovement(direction); 2798 final boolean isScroll = mBaseGridView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE; 2799 saveContext(recycler, state); 2800 if (movement == NEXT_ITEM) { 2801 if (isScroll || !mFocusOutEnd) { 2802 view = focused; 2803 } 2804 if (mScrollEnabled && !hasCreatedLastItem()) { 2805 processPendingMovement(true); 2806 view = focused; 2807 } 2808 } else if (movement == PREV_ITEM) { 2809 if (isScroll || !mFocusOutFront) { 2810 view = focused; 2811 } 2812 if (mScrollEnabled && !hasCreatedFirstItem()) { 2813 processPendingMovement(false); 2814 view = focused; 2815 } 2816 } 2817 leaveContext(); 2818 if (DEBUG) Log.v(getTag(), "onFocusSearchFailed returning view " + view); 2819 return view; 2820 } 2821 2822 boolean gridOnRequestFocusInDescendants(RecyclerView recyclerView, int direction, 2823 Rect previouslyFocusedRect) { 2824 switch (mFocusScrollStrategy) { 2825 case BaseGridView.FOCUS_SCROLL_ALIGNED: 2826 default: 2827 return gridOnRequestFocusInDescendantsAligned(recyclerView, 2828 direction, previouslyFocusedRect); 2829 case BaseGridView.FOCUS_SCROLL_PAGE: 2830 case BaseGridView.FOCUS_SCROLL_ITEM: 2831 return gridOnRequestFocusInDescendantsUnaligned(recyclerView, 2832 direction, previouslyFocusedRect); 2833 } 2834 } 2835 2836 private boolean gridOnRequestFocusInDescendantsAligned(RecyclerView recyclerView, 2837 int direction, Rect previouslyFocusedRect) { 2838 View view = findViewByPosition(mFocusPosition); 2839 if (view != null) { 2840 boolean result = view.requestFocus(direction, previouslyFocusedRect); 2841 if (!result && DEBUG) { 2842 Log.w(getTag(), "failed to request focus on " + view); 2843 } 2844 return result; 2845 } 2846 return false; 2847 } 2848 2849 private boolean gridOnRequestFocusInDescendantsUnaligned(RecyclerView recyclerView, 2850 int direction, Rect previouslyFocusedRect) { 2851 // focus to view not overlapping padding area to avoid scrolling in gaining focus 2852 int index; 2853 int increment; 2854 int end; 2855 int count = getChildCount(); 2856 if ((direction & View.FOCUS_FORWARD) != 0) { 2857 index = 0; 2858 increment = 1; 2859 end = count; 2860 } else { 2861 index = count - 1; 2862 increment = -1; 2863 end = -1; 2864 } 2865 int left = mWindowAlignment.mainAxis().getPaddingLow(); 2866 int right = mWindowAlignment.mainAxis().getClientSize() + left; 2867 for (int i = index; i != end; i += increment) { 2868 View child = getChildAt(i); 2869 if (child.getVisibility() == View.VISIBLE) { 2870 if (getViewMin(child) >= left && getViewMax(child) <= right) { 2871 if (child.requestFocus(direction, previouslyFocusedRect)) { 2872 return true; 2873 } 2874 } 2875 } 2876 } 2877 return false; 2878 } 2879 2880 private final static int PREV_ITEM = 0; 2881 private final static int NEXT_ITEM = 1; 2882 private final static int PREV_ROW = 2; 2883 private final static int NEXT_ROW = 3; 2884 2885 private int getMovement(int direction) { 2886 int movement = View.FOCUS_LEFT; 2887 2888 if (mOrientation == HORIZONTAL) { 2889 switch(direction) { 2890 case View.FOCUS_LEFT: 2891 movement = (!mReverseFlowPrimary) ? PREV_ITEM : NEXT_ITEM; 2892 break; 2893 case View.FOCUS_RIGHT: 2894 movement = (!mReverseFlowPrimary) ? NEXT_ITEM : PREV_ITEM; 2895 break; 2896 case View.FOCUS_UP: 2897 movement = PREV_ROW; 2898 break; 2899 case View.FOCUS_DOWN: 2900 movement = NEXT_ROW; 2901 break; 2902 } 2903 } else if (mOrientation == VERTICAL) { 2904 switch(direction) { 2905 case View.FOCUS_LEFT: 2906 movement = (!mReverseFlowPrimary) ? PREV_ROW : NEXT_ROW; 2907 break; 2908 case View.FOCUS_RIGHT: 2909 movement = (!mReverseFlowPrimary) ? NEXT_ROW : PREV_ROW; 2910 break; 2911 case View.FOCUS_UP: 2912 movement = PREV_ITEM; 2913 break; 2914 case View.FOCUS_DOWN: 2915 movement = NEXT_ITEM; 2916 break; 2917 } 2918 } 2919 2920 return movement; 2921 } 2922 2923 int getChildDrawingOrder(RecyclerView recyclerView, int childCount, int i) { 2924 View view = findViewByPosition(mFocusPosition); 2925 if (view == null) { 2926 return i; 2927 } 2928 int focusIndex = recyclerView.indexOfChild(view); 2929 // supposely 0 1 2 3 4 5 6 7 8 9, 4 is the center item 2930 // drawing order is 0 1 2 3 9 8 7 6 5 4 2931 if (i < focusIndex) { 2932 return i; 2933 } else if (i < childCount - 1) { 2934 return focusIndex + childCount - 1 - i; 2935 } else { 2936 return focusIndex; 2937 } 2938 } 2939 2940 @Override 2941 public void onAdapterChanged(RecyclerView.Adapter oldAdapter, 2942 RecyclerView.Adapter newAdapter) { 2943 if (DEBUG) Log.v(getTag(), "onAdapterChanged to " + newAdapter); 2944 if (oldAdapter != null) { 2945 discardLayoutInfo(); 2946 mFocusPosition = NO_POSITION; 2947 mFocusPositionOffset = 0; 2948 mChildrenStates.clear(); 2949 } 2950 if (newAdapter instanceof FacetProviderAdapter) { 2951 mFacetProviderAdapter = (FacetProviderAdapter) newAdapter; 2952 } else { 2953 mFacetProviderAdapter = null; 2954 } 2955 super.onAdapterChanged(oldAdapter, newAdapter); 2956 } 2957 2958 private void discardLayoutInfo() { 2959 mGrid = null; 2960 mRowSizeSecondary = null; 2961 mRowSecondarySizeRefresh = false; 2962 } 2963 2964 public void setLayoutEnabled(boolean layoutEnabled) { 2965 if (mLayoutEnabled != layoutEnabled) { 2966 mLayoutEnabled = layoutEnabled; 2967 requestLayout(); 2968 } 2969 } 2970 2971 void setChildrenVisibility(int visiblity) { 2972 mChildVisibility = visiblity; 2973 if (mChildVisibility != -1) { 2974 int count = getChildCount(); 2975 for (int i= 0; i < count; i++) { 2976 getChildAt(i).setVisibility(mChildVisibility); 2977 } 2978 } 2979 } 2980 2981 final static class SavedState implements Parcelable { 2982 2983 int index; // index inside adapter of the current view 2984 Bundle childStates = Bundle.EMPTY; 2985 2986 @Override 2987 public void writeToParcel(Parcel out, int flags) { 2988 out.writeInt(index); 2989 out.writeBundle(childStates); 2990 } 2991 2992 @SuppressWarnings("hiding") 2993 public static final Parcelable.Creator<SavedState> CREATOR = 2994 new Parcelable.Creator<SavedState>() { 2995 @Override 2996 public SavedState createFromParcel(Parcel in) { 2997 return new SavedState(in); 2998 } 2999 3000 @Override 3001 public SavedState[] newArray(int size) { 3002 return new SavedState[size]; 3003 } 3004 }; 3005 3006 @Override 3007 public int describeContents() { 3008 return 0; 3009 } 3010 3011 SavedState(Parcel in) { 3012 index = in.readInt(); 3013 childStates = in.readBundle(GridLayoutManager.class.getClassLoader()); 3014 } 3015 3016 SavedState() { 3017 } 3018 } 3019 3020 @Override 3021 public Parcelable onSaveInstanceState() { 3022 if (DEBUG) Log.v(getTag(), "onSaveInstanceState getSelection() " + getSelection()); 3023 SavedState ss = new SavedState(); 3024 // save selected index 3025 ss.index = getSelection(); 3026 // save offscreen child (state when they are recycled) 3027 Bundle bundle = mChildrenStates.saveAsBundle(); 3028 // save views currently is on screen (TODO save cached views) 3029 for (int i = 0, count = getChildCount(); i < count; i++) { 3030 View view = getChildAt(i); 3031 int position = getPositionByView(view); 3032 if (position != NO_POSITION) { 3033 bundle = mChildrenStates.saveOnScreenView(bundle, view, position); 3034 } 3035 } 3036 ss.childStates = bundle; 3037 return ss; 3038 } 3039 3040 void onChildRecycled(RecyclerView.ViewHolder holder) { 3041 final int position = holder.getAdapterPosition(); 3042 if (position != NO_POSITION) { 3043 mChildrenStates.saveOffscreenView(holder.itemView, position); 3044 } 3045 } 3046 3047 @Override 3048 public void onRestoreInstanceState(Parcelable state) { 3049 if (!(state instanceof SavedState)) { 3050 return; 3051 } 3052 SavedState loadingState = (SavedState)state; 3053 mFocusPosition = loadingState.index; 3054 mFocusPositionOffset = 0; 3055 mChildrenStates.loadFromBundle(loadingState.childStates); 3056 mForceFullLayout = true; 3057 requestLayout(); 3058 if (DEBUG) Log.v(getTag(), "onRestoreInstanceState mFocusPosition " + mFocusPosition); 3059 } 3060 3061 @Override 3062 public int getRowCountForAccessibility(RecyclerView.Recycler recycler, 3063 RecyclerView.State state) { 3064 if (mOrientation == HORIZONTAL && mGrid != null) { 3065 return mGrid.getNumRows(); 3066 } 3067 return super.getRowCountForAccessibility(recycler, state); 3068 } 3069 3070 @Override 3071 public int getColumnCountForAccessibility(RecyclerView.Recycler recycler, 3072 RecyclerView.State state) { 3073 if (mOrientation == VERTICAL && mGrid != null) { 3074 return mGrid.getNumRows(); 3075 } 3076 return super.getColumnCountForAccessibility(recycler, state); 3077 } 3078 3079 @Override 3080 public void onInitializeAccessibilityNodeInfoForItem(RecyclerView.Recycler recycler, 3081 RecyclerView.State state, View host, AccessibilityNodeInfoCompat info) { 3082 ViewGroup.LayoutParams lp = host.getLayoutParams(); 3083 if (mGrid == null || !(lp instanceof LayoutParams)) { 3084 super.onInitializeAccessibilityNodeInfoForItem(recycler, state, host, info); 3085 return; 3086 } 3087 LayoutParams glp = (LayoutParams) lp; 3088 int position = glp.getViewLayoutPosition(); 3089 int rowIndex = mGrid.getRowIndex(position); 3090 int guessSpanIndex = position / mGrid.getNumRows(); 3091 if (mOrientation == HORIZONTAL) { 3092 info.setCollectionItemInfo(AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain( 3093 rowIndex, 1, guessSpanIndex, 1, false, false)); 3094 } else { 3095 info.setCollectionItemInfo(AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain( 3096 guessSpanIndex, 1, rowIndex, 1, false, false)); 3097 } 3098 } 3099 3100 /* 3101 * Leanback widget is different than the default implementation because the "scroll" is driven 3102 * by selection change. 3103 */ 3104 @Override 3105 public boolean performAccessibilityAction(Recycler recycler, State state, int action, 3106 Bundle args) { 3107 saveContext(recycler, state); 3108 switch (action) { 3109 case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: 3110 // try to focus all the way to the last visible item on the same row. 3111 processSelectionMoves(false, -mState.getItemCount()); 3112 break; 3113 case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: 3114 processSelectionMoves(false, mState.getItemCount()); 3115 break; 3116 } 3117 leaveContext(); 3118 return true; 3119 } 3120 3121 /* 3122 * Move mFocusPosition multiple steps on the same row in main direction. 3123 * Stops when moves are all consumed or reach first/last visible item. 3124 * Returning remaining moves. 3125 */ 3126 private int processSelectionMoves(boolean preventScroll, int moves) { 3127 if (mGrid == null) { 3128 return moves; 3129 } 3130 int focusPosition = mFocusPosition; 3131 int focusedRow = focusPosition != NO_POSITION ? 3132 mGrid.getRowIndex(focusPosition) : NO_POSITION; 3133 View newSelected = null; 3134 for (int i = 0, count = getChildCount(); i < count && moves != 0; i++) { 3135 int index = moves > 0 ? i : count - 1 - i; 3136 final View child = getChildAt(index); 3137 if (!canScrollTo(child)) { 3138 continue; 3139 } 3140 int position = getPositionByIndex(index); 3141 int rowIndex = mGrid.getRowIndex(position); 3142 if (focusedRow == NO_POSITION) { 3143 focusPosition = position; 3144 newSelected = child; 3145 focusedRow = rowIndex; 3146 } else if (rowIndex == focusedRow) { 3147 if ((moves > 0 && position > focusPosition) 3148 || (moves < 0 && position < focusPosition)) { 3149 focusPosition = position; 3150 newSelected = child; 3151 if (moves > 0) { 3152 moves--; 3153 } else { 3154 moves++; 3155 } 3156 } 3157 } 3158 } 3159 if (newSelected != null) { 3160 if (preventScroll) { 3161 if (hasFocus()) { 3162 mInSelection = true; 3163 newSelected.requestFocus(); 3164 mInSelection = false; 3165 } 3166 mFocusPosition = focusPosition; 3167 mSubFocusPosition = 0; 3168 } else { 3169 scrollToView(newSelected, true); 3170 } 3171 } 3172 return moves; 3173 } 3174 3175 @Override 3176 public void onInitializeAccessibilityNodeInfo(Recycler recycler, State state, 3177 AccessibilityNodeInfoCompat info) { 3178 saveContext(recycler, state); 3179 if (mScrollEnabled && !hasCreatedFirstItem()) { 3180 info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD); 3181 info.setScrollable(true); 3182 } 3183 if (mScrollEnabled && !hasCreatedLastItem()) { 3184 info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD); 3185 info.setScrollable(true); 3186 } 3187 final AccessibilityNodeInfoCompat.CollectionInfoCompat collectionInfo 3188 = AccessibilityNodeInfoCompat.CollectionInfoCompat 3189 .obtain(getRowCountForAccessibility(recycler, state), 3190 getColumnCountForAccessibility(recycler, state), 3191 isLayoutHierarchical(recycler, state), 3192 getSelectionModeForAccessibility(recycler, state)); 3193 info.setCollectionInfo(collectionInfo); 3194 leaveContext(); 3195 } 3196} 3197