| 1 | /* |
| 2 | * Copyright 2018 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package androidx.recyclerview.widget; |
| 18 | |
| 19 | import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP_PREFIX; |
| 20 | |
| 21 | import android.annotation.SuppressLint; |
| 22 | import android.content.Context; |
| 23 | import android.graphics.PointF; |
| 24 | import android.os.Parcel; |
| 25 | import android.os.Parcelable; |
| 26 | import android.util.Log; |
| 27 | import android.view.View; |
| 28 | import android.view.ViewGroup; |
| 29 | import android.view.accessibility.AccessibilityEvent; |
| 30 | |
| 31 | import androidx.annotation.NonNull; |
| 32 | import androidx.annotation.RestrictTo; |
| 33 | import androidx.core.os.TraceCompat; |
| 34 | import androidx.core.view.ViewCompat; |
| 35 | |
| 36 | import org.telegram.messenger.BuildVars; |
| 37 | |
| 38 | import java.util.List; |
| 39 | |
| 40 | /** |
| 41 | * A {@link RecyclerView.LayoutManager} implementation which provides |
| 42 | * similar functionality to {@link android.widget.ListView}. |
| 43 | */ |
| 44 | public class LinearLayoutManager extends RecyclerView.LayoutManager implements |
| 45 | ItemTouchHelper.ViewDropHandler, RecyclerView.SmoothScroller.ScrollVectorProvider { |
| 46 | |
| 47 | private static final String TAG = "LinearLayoutManager"; |
| 48 | |
| 49 | static final boolean DEBUG = false; |
| 50 | |
| 51 | public static final int HORIZONTAL = RecyclerView.HORIZONTAL; |
| 52 | |
| 53 | public static final int VERTICAL = RecyclerView.VERTICAL; |
| 54 | |
| 55 | public static final int INVALID_OFFSET = Integer.MIN_VALUE; |
| 56 | |
| 57 | |
| 58 | /** |
| 59 | * While trying to find next view to focus, LayoutManager will not try to scroll more |
| 60 | * than this factor times the total space of the list. If layout is vertical, total space is the |
| 61 | * height minus padding, if layout is horizontal, total space is the width minus padding. |
| 62 | */ |
| 63 | private static final float MAX_SCROLL_FACTOR = 1 / 3f; |
| 64 | |
| 65 | /** |
| 66 | * Current orientation. Either {@link #HORIZONTAL} or {@link #VERTICAL} |
| 67 | */ |
| 68 | @RecyclerView.Orientation |
| 69 | int mOrientation = RecyclerView.DEFAULT_ORIENTATION; |
| 70 | |
| 71 | /** |
| 72 | * Helper class that keeps temporary layout state. |
| 73 | * It does not keep state after layout is complete but we still keep a reference to re-use |
| 74 | * the same object. |
| 75 | */ |
| 76 | private LayoutState mLayoutState; |
| 77 | |
| 78 | /** |
| 79 | * Many calculations are made depending on orientation. To keep it clean, this interface |
| 80 | * helps {@link LinearLayoutManager} make those decisions. |
| 81 | */ |
| 82 | OrientationHelper mOrientationHelper; |
| 83 | public boolean mIgnoreTopPadding = false; |
| 84 | |
| 85 | /** |
| 86 | * We need to track this so that we can ignore current position when it changes. |
| 87 | */ |
| 88 | private boolean mLastStackFromEnd; |
| 89 | |
| 90 | |
| 91 | /** |
| 92 | * Defines if layout should be calculated from end to start. |
| 93 | * |
| 94 | * @see #mShouldReverseLayout |
| 95 | */ |
| 96 | private boolean mReverseLayout = false; |
| 97 | |
| 98 | /** |
| 99 | * This keeps the final value for how LayoutManager should start laying out views. |
| 100 | * It is calculated by checking {@link #getReverseLayout()} and View's layout direction. |
| 101 | * {@link #onLayoutChildren(RecyclerView.Recycler, RecyclerView.State)} is run. |
| 102 | */ |
| 103 | boolean mShouldReverseLayout = false; |
| 104 | |
| 105 | /** |
| 106 | * Works the same way as {@link android.widget.AbsListView#setStackFromBottom(boolean)} and |
| 107 | * it supports both orientations. |
| 108 | * see {@link android.widget.AbsListView#setStackFromBottom(boolean)} |
| 109 | */ |
| 110 | private boolean mStackFromEnd = false; |
| 111 | |
| 112 | /** |
| 113 | * Works the same way as {@link android.widget.AbsListView#setSmoothScrollbarEnabled(boolean)}. |
| 114 | * see {@link android.widget.AbsListView#setSmoothScrollbarEnabled(boolean)} |
| 115 | */ |
| 116 | private boolean mSmoothScrollbarEnabled = true; |
| 117 | |
| 118 | /** |
| 119 | * When LayoutManager needs to scroll to a position, it sets this variable and requests a |
| 120 | * layout which will check this variable and re-layout accordingly. |
| 121 | */ |
| 122 | int mPendingScrollPosition = RecyclerView.NO_POSITION; |
| 123 | |
| 124 | boolean mPendingScrollPositionBottom = true; |
| 125 | |
| 126 | /** |
| 127 | * Used to keep the offset value when {@link #scrollToPositionWithOffset(int, int)} is |
| 128 | * called. |
| 129 | */ |
| 130 | int mPendingScrollPositionOffset = INVALID_OFFSET; |
| 131 | |
| 132 | private boolean mRecycleChildrenOnDetach; |
| 133 | |
| 134 | SavedState mPendingSavedState = null; |
| 135 | |
| 136 | /** |
| 137 | * Re-used variable to keep anchor information on re-layout. |
| 138 | * Anchor position and coordinate defines the reference point for LLM while doing a layout. |
| 139 | * */ |
| 140 | final AnchorInfo mAnchorInfo = new AnchorInfo(); |
| 141 | |
| 142 | /** |
| 143 | * Stashed to avoid allocation, currently only used in #fill() |
| 144 | */ |
| 145 | private final LayoutChunkResult mLayoutChunkResult = new LayoutChunkResult(); |
| 146 | |
| 147 | /** |
| 148 | * Number of items to prefetch when first coming on screen with new data. |
| 149 | */ |
| 150 | private int mInitialPrefetchItemCount = 2; |
| 151 | |
| 152 | // Reusable int array to be passed to method calls that mutate it in order to "return" two ints. |
| 153 | // This should only be used used transiently and should not be used to retain any state over |
| 154 | // time. |
| 155 | private int[] mReusableIntPair = new int[2]; |
| 156 | |
| 157 | private boolean needFixGap = true; |
| 158 | |
| 159 | /** |
| 160 | * Creates a vertical LinearLayoutManager |
| 161 | * |
| 162 | * @param context Current context, will be used to access resources. |
| 163 | */ |
| 164 | public LinearLayoutManager(Context context) { |
| 165 | this(context, RecyclerView.DEFAULT_ORIENTATION, false); |
| 166 | } |
| 167 | |
| 168 | /** |
| 169 | * @param context Current context, will be used to access resources. |
| 170 | * @param orientation Layout orientation. Should be {@link #HORIZONTAL} or {@link |
| 171 | * #VERTICAL}. |
| 172 | * @param reverseLayout When set to true, layouts from end to start. |
| 173 | */ |
| 174 | public LinearLayoutManager(Context context, @RecyclerView.Orientation int orientation, |
| 175 | boolean reverseLayout) { |
| 176 | setOrientation(orientation); |
| 177 | setReverseLayout(reverseLayout); |
| 178 | } |
| 179 | |
| 180 | @Override |
| 181 | public boolean isAutoMeasureEnabled() { |
| 182 | return true; |
| 183 | } |
| 184 | |
| 185 | /** |
| 186 | * {@inheritDoc} |
| 187 | */ |
| 188 | @Override |
| 189 | public RecyclerView.LayoutParams generateDefaultLayoutParams() { |
| 190 | return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, |
| 191 | ViewGroup.LayoutParams.WRAP_CONTENT); |
| 192 | } |
| 193 | |
| 194 | /** |
| 195 | * Returns whether LayoutManager will recycle its children when it is detached from |
| 196 | * RecyclerView. |
| 197 | * |
| 198 | * @return true if LayoutManager will recycle its children when it is detached from |
| 199 | * RecyclerView. |
| 200 | */ |
| 201 | public boolean getRecycleChildrenOnDetach() { |
| 202 | return mRecycleChildrenOnDetach; |
| 203 | } |
| 204 | |
| 205 | /** |
| 206 | * Set whether LayoutManager will recycle its children when it is detached from |
| 207 | * RecyclerView. |
| 208 | * <p> |
| 209 | * If you are using a {@link RecyclerView.RecycledViewPool}, it might be a good idea to set |
| 210 | * this flag to <code>true</code> so that views will be available to other RecyclerViews |
| 211 | * immediately. |
| 212 | * <p> |
| 213 | * Note that, setting this flag will result in a performance drop if RecyclerView |
| 214 | * is restored. |
| 215 | * |
| 216 | * @param recycleChildrenOnDetach Whether children should be recycled in detach or not. |
| 217 | */ |
| 218 | public void setRecycleChildrenOnDetach(boolean recycleChildrenOnDetach) { |
| 219 | mRecycleChildrenOnDetach = recycleChildrenOnDetach; |
| 220 | } |
| 221 | |
| 222 | @Override |
| 223 | public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) { |
| 224 | super.onDetachedFromWindow(view, recycler); |
| 225 | if (mRecycleChildrenOnDetach) { |
| 226 | removeAndRecycleAllViews(recycler); |
| 227 | recycler.clear(); |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | @Override |
| 232 | public void onInitializeAccessibilityEvent(AccessibilityEvent event) { |
| 233 | super.onInitializeAccessibilityEvent(event); |
| 234 | if (getChildCount() > 0) { |
| 235 | event.setFromIndex(findFirstVisibleItemPosition()); |
| 236 | event.setToIndex(findLastVisibleItemPosition()); |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | @Override |
| 241 | public Parcelable onSaveInstanceState() { |
| 242 | if (mPendingSavedState != null) { |
| 243 | return new SavedState(mPendingSavedState); |
| 244 | } |
| 245 | SavedState state = new SavedState(); |
| 246 | if (getChildCount() > 0) { |
| 247 | ensureLayoutState(); |
| 248 | boolean didLayoutFromEnd = mLastStackFromEnd ^ mShouldReverseLayout; |
| 249 | state.mAnchorLayoutFromEnd = didLayoutFromEnd; |
| 250 | if (didLayoutFromEnd) { |
| 251 | final View refChild = getChildClosestToEnd(); |
| 252 | state.mAnchorOffset = mOrientationHelper.getEndAfterPadding() |
| 253 | - mOrientationHelper.getDecoratedEnd(refChild); |
| 254 | state.mAnchorPosition = getPosition(refChild); |
| 255 | } else { |
| 256 | final View refChild = getChildClosestToStart(); |
| 257 | state.mAnchorPosition = getPosition(refChild); |
| 258 | state.mAnchorOffset = mOrientationHelper.getDecoratedStart(refChild) |
| 259 | - mOrientationHelper.getStartAfterPadding(); |
| 260 | } |
| 261 | } else { |
| 262 | state.invalidateAnchor(); |
| 263 | } |
| 264 | return state; |
| 265 | } |
| 266 | |
| 267 | @Override |
| 268 | public void onRestoreInstanceState(Parcelable state) { |
| 269 | if (state instanceof SavedState) { |
| 270 | mPendingSavedState = (SavedState) state; |
| 271 | requestLayout(); |
| 272 | if (DEBUG) { |
| 273 | Log.d(TAG, "loaded saved state"); |
| 274 | } |
| 275 | } else if (DEBUG) { |
| 276 | Log.d(TAG, "invalid saved state class"); |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | /** |
| 281 | * @return true if {@link #getOrientation()} is {@link #HORIZONTAL} |
| 282 | */ |
| 283 | @Override |
| 284 | public boolean canScrollHorizontally() { |
| 285 | return mOrientation == HORIZONTAL; |
| 286 | } |
| 287 | |
| 288 | /** |
| 289 | * @return true if {@link #getOrientation()} is {@link #VERTICAL} |
| 290 | */ |
| 291 | @Override |
| 292 | public boolean canScrollVertically() { |
| 293 | return mOrientation == VERTICAL; |
| 294 | } |
| 295 | |
| 296 | /** |
| 297 | * Compatibility support for {@link android.widget.AbsListView#setStackFromBottom(boolean)} |
| 298 | */ |
| 299 | public void setStackFromEnd(boolean stackFromEnd) { |
| 300 | assertNotInLayoutOrScroll(null); |
| 301 | if (mStackFromEnd == stackFromEnd) { |
| 302 | return; |
| 303 | } |
| 304 | mStackFromEnd = stackFromEnd; |
| 305 | requestLayout(); |
| 306 | } |
| 307 | |
| 308 | public boolean getStackFromEnd() { |
| 309 | return mStackFromEnd; |
| 310 | } |
| 311 | |
| 312 | /** |
| 313 | * Returns the current orientation of the layout. |
| 314 | * |
| 315 | * @return Current orientation, either {@link #HORIZONTAL} or {@link #VERTICAL} |
| 316 | * @see #setOrientation(int) |
| 317 | */ |
| 318 | @RecyclerView.Orientation |
| 319 | public int getOrientation() { |
| 320 | return mOrientation; |
| 321 | } |
| 322 | |
| 323 | /** |
| 324 | * Sets the orientation of the layout. {@link LinearLayoutManager} |
| 325 | * will do its best to keep scroll position. |
| 326 | * |
| 327 | * @param orientation {@link #HORIZONTAL} or {@link #VERTICAL} |
| 328 | */ |
| 329 | public void setOrientation(@RecyclerView.Orientation int orientation) { |
| 330 | if (orientation != HORIZONTAL && orientation != VERTICAL) { |
| 331 | throw new IllegalArgumentException("invalid orientation:" + orientation); |
| 332 | } |
| 333 | |
| 334 | assertNotInLayoutOrScroll(null); |
| 335 | |
| 336 | if (orientation != mOrientation || mOrientationHelper == null) { |
| 337 | mOrientationHelper = |
| 338 | OrientationHelper.createOrientationHelper(this, orientation); |
| 339 | mAnchorInfo.mOrientationHelper = mOrientationHelper; |
| 340 | mOrientation = orientation; |
| 341 | requestLayout(); |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | /** |
| 346 | * Calculates the view layout order. (e.g. from end to start or start to end) |
| 347 | * RTL layout support is applied automatically. So if layout is RTL and |
| 348 | * {@link #getReverseLayout()} is {@code true}, elements will be laid out starting from left. |
| 349 | */ |
| 350 | private void resolveShouldLayoutReverse() { |
| 351 | // A == B is the same result, but we rather keep it readable |
| 352 | if (mOrientation == VERTICAL || !isLayoutRTL()) { |
| 353 | mShouldReverseLayout = mReverseLayout; |
| 354 | } else { |
| 355 | mShouldReverseLayout = !mReverseLayout; |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | /** |
| 360 | * Returns if views are laid out from the opposite direction of the layout. |
| 361 | * |
| 362 | * @return If layout is reversed or not. |
| 363 | * @see #setReverseLayout(boolean) |
| 364 | */ |
| 365 | public boolean getReverseLayout() { |
| 366 | return mReverseLayout; |
| 367 | } |
| 368 | |
| 369 | /** |
| 370 | * Used to reverse item traversal and layout order. |
| 371 | * This behaves similar to the layout change for RTL views. When set to true, first item is |
| 372 | * laid out at the end of the UI, second item is laid out before it etc. |
| 373 | * |
| 374 | * For horizontal layouts, it depends on the layout direction. |
| 375 | * When set to true, If {@link RecyclerView} is LTR, than it will |
| 376 | * layout from RTL, if {@link RecyclerView}} is RTL, it will layout |
| 377 | * from LTR. |
| 378 | * |
| 379 | * If you are looking for the exact same behavior of |
| 380 | * {@link android.widget.AbsListView#setStackFromBottom(boolean)}, use |
| 381 | * {@link #setStackFromEnd(boolean)} |
| 382 | */ |
| 383 | public void setReverseLayout(boolean reverseLayout) { |
| 384 | assertNotInLayoutOrScroll(null); |
| 385 | if (reverseLayout == mReverseLayout) { |
| 386 | return; |
| 387 | } |
| 388 | mReverseLayout = reverseLayout; |
| 389 | requestLayout(); |
| 390 | } |
| 391 | |
| 392 | /** |
| 393 | * {@inheritDoc} |
| 394 | */ |
| 395 | @Override |
| 396 | public View findViewByPosition(int position) { |
| 397 | final int childCount = getChildCount(); |
| 398 | if (childCount == 0) { |
| 399 | return null; |
| 400 | } |
| 401 | final int firstChild = getPosition(getChildAt(0)); |
| 402 | final int viewPosition = position - firstChild; |
| 403 | if (viewPosition >= 0 && viewPosition < childCount) { |
| 404 | final View child = getChildAt(viewPosition); |
| 405 | if (getPosition(child) == position) { |
| 406 | return child; // in pre-layout, this may not match |
| 407 | } |
| 408 | } |
| 409 | // fallback to traversal. This might be necessary in pre-layout. |
| 410 | return super.findViewByPosition(position); |
| 411 | } |
| 412 | |
| 413 | /** |
| 414 | * <p>Returns the amount of extra space that should be laid out by LayoutManager.</p> |
| 415 | * |
| 416 | * <p>By default, {@link LinearLayoutManager} lays out 1 extra page |
| 417 | * of items while smooth scrolling and 0 otherwise. You can override this method to implement |
| 418 | * your custom layout pre-cache logic.</p> |
| 419 | * |
| 420 | * <p><strong>Note:</strong>Laying out invisible elements generally comes with significant |
| 421 | * performance cost. It's typically only desirable in places like smooth scrolling to an unknown |
| 422 | * location, where 1) the extra content helps LinearLayoutManager know in advance when its |
| 423 | * target is approaching, so it can decelerate early and smoothly and 2) while motion is |
| 424 | * continuous.</p> |
| 425 | * |
| 426 | * <p>Extending the extra layout space is especially expensive if done while the user may change |
| 427 | * scrolling direction. Changing direction will cause the extra layout space to swap to the |
| 428 | * opposite side of the viewport, incurring many rebinds/recycles, unless the cache is large |
| 429 | * enough to handle it.</p> |
| 430 | * |
| 431 | * @return The extra space that should be laid out (in pixels). |
| 432 | * @deprecated Use {@link #calculateExtraLayoutSpace(RecyclerView.State, int[])} instead. |
| 433 | */ |
| 434 | @SuppressWarnings("DeprecatedIsStillUsed") |
| 435 | @Deprecated |
| 436 | protected int getExtraLayoutSpace(RecyclerView.State state) { |
| 437 | if (state.hasTargetScrollPosition()) { |
| 438 | return mOrientationHelper.getTotalSpace(); |
| 439 | } else { |
| 440 | return 0; |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | /** |
| 445 | * <p>Calculates the amount of extra space (in pixels) that should be laid out by {@link |
| 446 | * LinearLayoutManager} and stores the result in {@code extraLayoutSpace}. {@code |
| 447 | * extraLayoutSpace[0]} should be used for the extra space at the top/left, and {@code |
| 448 | * extraLayoutSpace[1]} should be used for the extra space at the bottom/right (depending on the |
| 449 | * orientation). Thus, the side where it is applied is unaffected by {@link |
| 450 | * #getLayoutDirection()} (LTR vs RTL), {@link #getStackFromEnd()} and {@link |
| 451 | * #getReverseLayout()}. Negative values are ignored.</p> |
| 452 | * |
| 453 | * <p>By default, {@code LinearLayoutManager} lays out 1 extra page of items while smooth |
| 454 | * scrolling, in the direction of the scroll, and no extra space is laid out in all other |
| 455 | * situations. You can override this method to implement your own custom pre-cache logic. Use |
| 456 | * {@link RecyclerView.State#hasTargetScrollPosition()} to find out if a smooth scroll to a |
| 457 | * position is in progress, and {@link RecyclerView.State#getTargetScrollPosition()} to find out |
| 458 | * which item it is scrolling to.</p> |
| 459 | * |
| 460 | * <p><strong>Note:</strong>Laying out extra items generally comes with significant performance |
| 461 | * cost. It's typically only desirable in places like smooth scrolling to an unknown location, |
| 462 | * where 1) the extra content helps LinearLayoutManager know in advance when its target is |
| 463 | * approaching, so it can decelerate early and smoothly and 2) while motion is continuous.</p> |
| 464 | * |
| 465 | * <p>Extending the extra layout space is especially expensive if done while the user may change |
| 466 | * scrolling direction. In the default implementation, changing direction will cause the extra |
| 467 | * layout space to swap to the opposite side of the viewport, incurring many rebinds/recycles, |
| 468 | * unless the cache is large enough to handle it.</p> |
| 469 | */ |
| 470 | protected void calculateExtraLayoutSpace(@NonNull RecyclerView.State state, |
| 471 | @NonNull int[] extraLayoutSpace) { |
| 472 | int extraLayoutSpaceStart = 0; |
| 473 | int extraLayoutSpaceEnd = 0; |
| 474 | |
| 475 | // If calculateExtraLayoutSpace is not overridden, call the |
| 476 | // deprecated getExtraLayoutSpace for backwards compatibility |
| 477 | @SuppressWarnings("deprecation") |
| 478 | int extraScrollSpace = getExtraLayoutSpace(state); |
| 479 | if (mLayoutState.mLayoutDirection == LayoutState.LAYOUT_START) { |
| 480 | extraLayoutSpaceStart = extraScrollSpace; |
| 481 | } else { |
| 482 | extraLayoutSpaceEnd = extraScrollSpace; |
| 483 | } |
| 484 | |
| 485 | extraLayoutSpace[0] = extraLayoutSpaceStart; |
| 486 | extraLayoutSpace[1] = extraLayoutSpaceEnd; |
| 487 | } |
| 488 | |
| 489 | @Override |
| 490 | public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, |
| 491 | int position) { |
| 492 | LinearSmoothScroller linearSmoothScroller = |
| 493 | new LinearSmoothScroller(recyclerView.getContext()); |
| 494 | linearSmoothScroller.setTargetPosition(position); |
| 495 | startSmoothScroll(linearSmoothScroller); |
| 496 | } |
| 497 | |
| 498 | @Override |
| 499 | public PointF computeScrollVectorForPosition(int targetPosition) { |
| 500 | if (getChildCount() == 0) { |
| 501 | return null; |
| 502 | } |
| 503 | final int firstChildPos = getPosition(getChildAt(0)); |
| 504 | final int direction = targetPosition < firstChildPos != mShouldReverseLayout ? -1 : 1; |
| 505 | if (mOrientation == HORIZONTAL) { |
| 506 | return new PointF(direction, 0); |
| 507 | } else { |
| 508 | return new PointF(0, direction); |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | /** |
| 513 | * {@inheritDoc} |
| 514 | */ |
| 515 | @Override |
| 516 | public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { |
| 517 | // layout algorithm: |
| 518 | // 1) by checking children and other variables, find an anchor coordinate and an anchor |
| 519 | // item position. |
| 520 | // 2) fill towards start, stacking from bottom |
| 521 | // 3) fill towards end, stacking from top |
| 522 | // 4) scroll to fulfill requirements like stack from bottom. |
| 523 | // create layout state |
| 524 | if (DEBUG) { |
| 525 | Log.d(TAG, "is pre layout:" + state.isPreLayout()); |
| 526 | } |
| 527 | if (mPendingSavedState != null || mPendingScrollPosition != RecyclerView.NO_POSITION) { |
| 528 | if (state.getItemCount() == 0) { |
| 529 | removeAndRecycleAllViews(recycler); |
| 530 | return; |
| 531 | } |
| 532 | } |
| 533 | if (mPendingSavedState != null && mPendingSavedState.hasValidAnchor()) { |
| 534 | mPendingScrollPosition = mPendingSavedState.mAnchorPosition; |
| 535 | } |
| 536 | |
| 537 | ensureLayoutState(); |
| 538 | mLayoutState.mRecycle = false; |
| 539 | // resolve layout direction |
| 540 | resolveShouldLayoutReverse(); |
| 541 | |
| 542 | final View focused = getFocusedChild(); |
| 543 | if (!mAnchorInfo.mValid || mPendingScrollPosition != RecyclerView.NO_POSITION |
| 544 | || mPendingSavedState != null) { |
| 545 | mAnchorInfo.reset(); |
| 546 | mAnchorInfo.mLayoutFromEnd = mShouldReverseLayout ^ mStackFromEnd; |
| 547 | // calculate anchor position and coordinate |
| 548 | updateAnchorInfoForLayout(recycler, state, mAnchorInfo); |
| 549 | mAnchorInfo.mValid = true; |
| 550 | } else if (focused != null && (mOrientationHelper.getDecoratedStart(focused) |
| 551 | >= mOrientationHelper.getEndAfterPadding() |
| 552 | || mOrientationHelper.getDecoratedEnd(focused) |
| 553 | <= mOrientationHelper.getStartAfterPadding())) { |
| 554 | // This case relates to when the anchor child is the focused view and due to layout |
| 555 | // shrinking the focused view fell outside the viewport, e.g. when soft keyboard shows |
| 556 | // up after tapping an EditText which shrinks RV causing the focused view (The tapped |
| 557 | // EditText which is the anchor child) to get kicked out of the screen. Will update the |
| 558 | // anchor coordinate in order to make sure that the focused view is laid out. Otherwise, |
| 559 | // the available space in layoutState will be calculated as negative preventing the |
| 560 | // focused view from being laid out in fill. |
| 561 | // Note that we won't update the anchor position between layout passes (refer to |
| 562 | // TestResizingRelayoutWithAutoMeasure), which happens if we were to call |
| 563 | // updateAnchorInfoForLayout for an anchor that's not the focused view (e.g. a reference |
| 564 | // child which can change between layout passes). |
| 565 | mAnchorInfo.assignFromViewAndKeepVisibleRect(focused, getPosition(focused)); |
| 566 | } |
| 567 | if (DEBUG) { |
| 568 | Log.d(TAG, "Anchor info:" + mAnchorInfo); |
| 569 | } |
| 570 | |
| 571 | // LLM may decide to layout items for "extra" pixels to account for scrolling target, |
| 572 | // caching or predictive animations. |
| 573 | |
| 574 | mLayoutState.mLayoutDirection = mLayoutState.mLastScrollDelta >= 0 |
| 575 | ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START; |
| 576 | mReusableIntPair[0] = 0; |
| 577 | mReusableIntPair[1] = 0; |
| 578 | calculateExtraLayoutSpace(state, mReusableIntPair); |
| 579 | int extraForStart = Math.max(0, mReusableIntPair[0]) |
| 580 | + mOrientationHelper.getStartAfterPadding(); |
| 581 | int extraForEnd = Math.max(0, mReusableIntPair[1]) |
| 582 | + mOrientationHelper.getEndPadding(); |
| 583 | if (state.isPreLayout() && mPendingScrollPosition != RecyclerView.NO_POSITION |
| 584 | && mPendingScrollPositionOffset != INVALID_OFFSET) { |
| 585 | // if the child is visible and we are going to move it around, we should layout |
| 586 | // extra items in the opposite direction to make sure new items animate nicely |
| 587 | // instead of just fading in |
| 588 | final View existing = findViewByPosition(mPendingScrollPosition); |
| 589 | if (existing != null) { |
| 590 | final int current; |
| 591 | final int upcomingOffset; |
| 592 | if (mPendingScrollPositionBottom) { |
| 593 | current = mOrientationHelper.getEndAfterPadding() |
| 594 | - mOrientationHelper.getDecoratedEnd(existing); |
| 595 | upcomingOffset = current - mPendingScrollPositionOffset; |
| 596 | } else { |
| 597 | current = mOrientationHelper.getDecoratedStart(existing) |
| 598 | - mOrientationHelper.getStartAfterPadding(); |
| 599 | upcomingOffset = mPendingScrollPositionOffset - current; |
| 600 | } |
| 601 | if (upcomingOffset > 0) { |
| 602 | extraForStart += upcomingOffset; |
| 603 | } else { |
| 604 | extraForEnd -= upcomingOffset; |
| 605 | } |
| 606 | } |
| 607 | } |
| 608 | int startOffset; |
| 609 | int endOffset; |
| 610 | final int firstLayoutDirection; |
| 611 | if (mAnchorInfo.mLayoutFromEnd) { |
| 612 | firstLayoutDirection = mShouldReverseLayout ? LayoutState.ITEM_DIRECTION_TAIL |
| 613 | : LayoutState.ITEM_DIRECTION_HEAD; |
| 614 | } else { |
| 615 | firstLayoutDirection = mShouldReverseLayout ? LayoutState.ITEM_DIRECTION_HEAD |
| 616 | : LayoutState.ITEM_DIRECTION_TAIL; |
| 617 | } |
| 618 | |
| 619 | onAnchorReady(recycler, state, mAnchorInfo, firstLayoutDirection); |
| 620 | detachAndScrapAttachedViews(recycler); |
| 621 | mLayoutState.mInfinite = resolveIsInfinite(); |
| 622 | mLayoutState.mIsPreLayout = state.isPreLayout(); |
| 623 | // noRecycleSpace not needed: recycling doesn't happen in below's fill |
| 624 | // invocations because mScrollingOffset is set to SCROLLING_OFFSET_NaN |
| 625 | mLayoutState.mNoRecycleSpace = 0; |
| 626 | if (mAnchorInfo.mLayoutFromEnd) { |
| 627 | // fill towards start |
| 628 | updateLayoutStateToFillStart(mAnchorInfo); |
| 629 | mLayoutState.mExtraFillSpace = extraForStart; |
| 630 | fill(recycler, mLayoutState, state, false); |
| 631 | startOffset = mLayoutState.mOffset; |
| 632 | final int firstElement = mLayoutState.mCurrentPosition; |
| 633 | if (mLayoutState.mAvailable > 0) { |
| 634 | extraForEnd += mLayoutState.mAvailable; |
| 635 | } |
| 636 | // fill towards end |
| 637 | updateLayoutStateToFillEnd(mAnchorInfo); |
| 638 | mLayoutState.mExtraFillSpace = extraForEnd; |
| 639 | mLayoutState.mCurrentPosition += mLayoutState.mItemDirection; |
| 640 | fill(recycler, mLayoutState, state, false); |
| 641 | endOffset = mLayoutState.mOffset; |
| 642 | |
| 643 | if (mLayoutState.mAvailable > 0) { |
| 644 | // end could not consume all. add more items towards start |
| 645 | extraForStart = mLayoutState.mAvailable; |
| 646 | updateLayoutStateToFillStart(firstElement, startOffset); |
| 647 | mLayoutState.mExtraFillSpace = extraForStart; |
| 648 | fill(recycler, mLayoutState, state, false); |
| 649 | startOffset = mLayoutState.mOffset; |
| 650 | } |
| 651 | } else { |
| 652 | // fill towards end |
| 653 | updateLayoutStateToFillEnd(mAnchorInfo); |
| 654 | mLayoutState.mExtraFillSpace = extraForEnd; |
| 655 | fill(recycler, mLayoutState, state, false); |
| 656 | endOffset = mLayoutState.mOffset; |
| 657 | final int lastElement = mLayoutState.mCurrentPosition; |
| 658 | if (mLayoutState.mAvailable > 0) { |
| 659 | extraForStart += mLayoutState.mAvailable; |
| 660 | } |
| 661 | // fill towards start |
| 662 | updateLayoutStateToFillStart(mAnchorInfo); |
| 663 | mLayoutState.mExtraFillSpace = extraForStart; |
| 664 | mLayoutState.mCurrentPosition += mLayoutState.mItemDirection; |
| 665 | fill(recycler, mLayoutState, state, false); |
| 666 | startOffset = mLayoutState.mOffset; |
| 667 | |
| 668 | if (mLayoutState.mAvailable > 0) { |
| 669 | extraForEnd = mLayoutState.mAvailable; |
| 670 | // start could not consume all it should. add more items towards end |
| 671 | updateLayoutStateToFillEnd(lastElement, endOffset); |
| 672 | mLayoutState.mExtraFillSpace = extraForEnd; |
| 673 | fill(recycler, mLayoutState, state, false); |
| 674 | endOffset = mLayoutState.mOffset; |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | // changes may cause gaps on the UI, try to fix them. |
| 679 | // TODO we can probably avoid this if neither stackFromEnd/reverseLayout/RTL values have |
| 680 | // changed |
| 681 | if (getChildCount() > 0) { |
| 682 | // because layout from end may be changed by scroll to position |
| 683 | // we re-calculate it. |
| 684 | // find which side we should check for gaps. |
| 685 | if (mShouldReverseLayout ^ mStackFromEnd) { |
| 686 | int fixOffset = fixLayoutEndGap(endOffset, recycler, state, true); |
| 687 | startOffset += fixOffset; |
| 688 | endOffset += fixOffset; |
| 689 | fixOffset = fixLayoutStartGap(startOffset, recycler, state, false); |
| 690 | startOffset += fixOffset; |
| 691 | endOffset += fixOffset; |
| 692 | } else { |
| 693 | int fixOffset = fixLayoutStartGap(startOffset, recycler, state, true); |
| 694 | startOffset += fixOffset; |
| 695 | endOffset += fixOffset; |
| 696 | fixOffset = fixLayoutEndGap(endOffset, recycler, state, false); |
| 697 | startOffset += fixOffset; |
| 698 | endOffset += fixOffset; |
| 699 | } |
| 700 | } |
| 701 | layoutForPredictiveAnimations(recycler, state, startOffset, endOffset); |
| 702 | if (!state.isPreLayout()) { |
| 703 | mOrientationHelper.onLayoutComplete(); |
| 704 | } else { |
| 705 | mAnchorInfo.reset(); |
| 706 | } |
| 707 | mLastStackFromEnd = mStackFromEnd; |
| 708 | // if (DEBUG) { |
| 709 | // validateChildOrder(); |
| 710 | // } |
| 711 | } |
| 712 | |
| 713 | @Override |
| 714 | public void onLayoutCompleted(RecyclerView.State state) { |
| 715 | super.onLayoutCompleted(state); |
| 716 | mPendingSavedState = null; // we don't need this anymore |
| 717 | mPendingScrollPosition = RecyclerView.NO_POSITION; |
| 718 | mPendingScrollPositionOffset = INVALID_OFFSET; |
| 719 | mAnchorInfo.reset(); |
| 720 | } |
| 721 | |
| 722 | /** |
| 723 | * Method called when Anchor position is decided. Extending class can setup accordingly or |
| 724 | * even update anchor info if necessary. |
| 725 | * @param recycler The recycler for the layout |
| 726 | * @param state The layout state |
| 727 | * @param anchorInfo The mutable POJO that keeps the position and offset. |
| 728 | * @param firstLayoutItemDirection The direction of the first layout filling in terms of adapter |
| 729 | * indices. |
| 730 | */ |
| 731 | void onAnchorReady(RecyclerView.Recycler recycler, RecyclerView.State state, |
| 732 | AnchorInfo anchorInfo, int firstLayoutItemDirection) { |
| 733 | } |
| 734 | |
| 735 | /** |
| 736 | * If necessary, layouts new items for predictive animations |
| 737 | */ |
| 738 | private void layoutForPredictiveAnimations(RecyclerView.Recycler recycler, |
| 739 | RecyclerView.State state, int startOffset, |
| 740 | int endOffset) { |
| 741 | // If there are scrap children that we did not layout, we need to find where they did go |
| 742 | // and layout them accordingly so that animations can work as expected. |
| 743 | // This case may happen if new views are added or an existing view expands and pushes |
| 744 | // another view out of bounds. |
| 745 | if (!state.willRunPredictiveAnimations() || getChildCount() == 0 || state.isPreLayout() |
| 746 | || !supportsPredictiveItemAnimations()) { |
| 747 | return; |
| 748 | } |
| 749 | // to make the logic simpler, we calculate the size of children and call fill. |
| 750 | int scrapExtraStart = 0, scrapExtraEnd = 0; |
| 751 | final List<RecyclerView.ViewHolder> scrapList = recycler.getScrapList(); |
| 752 | final int scrapSize = scrapList.size(); |
| 753 | final int firstChildPos = getPosition(getChildAt(0)); |
| 754 | for (int i = 0; i < scrapSize; i++) { |
| 755 | RecyclerView.ViewHolder scrap = scrapList.get(i); |
| 756 | if (scrap.isRemoved()) { |
| 757 | continue; |
| 758 | } |
| 759 | final int position = scrap.getLayoutPosition(); |
| 760 | final int direction = position < firstChildPos != mShouldReverseLayout |
| 761 | ? LayoutState.LAYOUT_START : LayoutState.LAYOUT_END; |
| 762 | if (direction == LayoutState.LAYOUT_START) { |
| 763 | scrapExtraStart += mOrientationHelper.getDecoratedMeasurement(scrap.itemView); |
| 764 | } else { |
| 765 | scrapExtraEnd += mOrientationHelper.getDecoratedMeasurement(scrap.itemView); |
| 766 | } |
| 767 | } |
| 768 | |
| 769 | if (DEBUG) { |
| 770 | Log.d(TAG, "for unused scrap, decided to add " + scrapExtraStart |
| 771 | + " towards start and " + scrapExtraEnd + " towards end"); |
| 772 | } |
| 773 | mLayoutState.mScrapList = scrapList; |
| 774 | if (scrapExtraStart > 0) { |
| 775 | View anchor = getChildClosestToStart(); |
| 776 | updateLayoutStateToFillStart(getPosition(anchor), startOffset); |
| 777 | mLayoutState.mExtraFillSpace = scrapExtraStart; |
| 778 | mLayoutState.mAvailable = 0; |
| 779 | mLayoutState.assignPositionFromScrapList(); |
| 780 | fill(recycler, mLayoutState, state, false); |
| 781 | } |
| 782 | |
| 783 | if (scrapExtraEnd > 0) { |
| 784 | View anchor = getChildClosestToEnd(); |
| 785 | updateLayoutStateToFillEnd(getPosition(anchor), endOffset); |
| 786 | mLayoutState.mExtraFillSpace = scrapExtraEnd; |
| 787 | mLayoutState.mAvailable = 0; |
| 788 | mLayoutState.assignPositionFromScrapList(); |
| 789 | fill(recycler, mLayoutState, state, false); |
| 790 | } |
| 791 | mLayoutState.mScrapList = null; |
| 792 | } |
| 793 | |
| 794 | private void updateAnchorInfoForLayout(RecyclerView.Recycler recycler, RecyclerView.State state, |
| 795 | AnchorInfo anchorInfo) { |
| 796 | if (updateAnchorFromPendingData(state, anchorInfo)) { |
| 797 | if (DEBUG) { |
| 798 | Log.d(TAG, "updated anchor info from pending information"); |
| 799 | } |
| 800 | return; |
| 801 | } |
| 802 | |
| 803 | if (updateAnchorFromChildren(recycler, state, anchorInfo)) { |
| 804 | if (DEBUG) { |
| 805 | Log.d(TAG, "updated anchor info from existing children"); |
| 806 | } |
| 807 | return; |
| 808 | } |
| 809 | if (DEBUG) { |
| 810 | Log.d(TAG, "deciding anchor info for fresh state"); |
| 811 | } |
| 812 | anchorInfo.assignCoordinateFromPadding(); |
| 813 | anchorInfo.mPosition = mStackFromEnd ? state.getItemCount() - 1 : 0; |
| 814 | } |
| 815 | |
| 816 | /** |
| 817 | * Finds an anchor child from existing Views. Most of the time, this is the view closest to |
| 818 | * start or end that has a valid position (e.g. not removed). |
| 819 | * <p> |
| 820 | * If a child has focus, it is given priority. |
| 821 | */ |
| 822 | private boolean updateAnchorFromChildren(RecyclerView.Recycler recycler, |
| 823 | RecyclerView.State state, AnchorInfo anchorInfo) { |
| 824 | if (getChildCount() == 0) { |
| 825 | return false; |
| 826 | } |
| 827 | final View focused = getFocusedChild(); |
| 828 | if (focused != null && anchorInfo.isViewValidAsAnchor(focused, state)) { |
| 829 | anchorInfo.assignFromViewAndKeepVisibleRect(focused, getPosition(focused)); |
| 830 | return true; |
| 831 | } |
| 832 | if (mLastStackFromEnd != mStackFromEnd) { |
| 833 | return false; |
| 834 | } |
| 835 | View referenceChild = anchorInfo.mLayoutFromEnd |
| 836 | ? findReferenceChildClosestToEnd(recycler, state) |
| 837 | : findReferenceChildClosestToStart(recycler, state); |
| 838 | if (referenceChild != null) { |
| 839 | anchorInfo.assignFromView(referenceChild, getPosition(referenceChild)); |
| 840 | // If all visible views are removed in 1 pass, reference child might be out of bounds. |
| 841 | // If that is the case, offset it back to 0 so that we use these pre-layout children. |
| 842 | if (!state.isPreLayout() && supportsPredictiveItemAnimations()) { |
| 843 | // validate this child is at least partially visible. if not, offset it to start |
| 844 | final boolean notVisible = |
| 845 | mOrientationHelper.getDecoratedStart(referenceChild) >= mOrientationHelper |
| 846 | .getEndAfterPadding() |
| 847 | || mOrientationHelper.getDecoratedEnd(referenceChild) |
| 848 | < mOrientationHelper.getStartAfterPadding(); |
| 849 | if (notVisible) { |
| 850 | anchorInfo.mCoordinate = anchorInfo.mLayoutFromEnd |
| 851 | ? mOrientationHelper.getEndAfterPadding() |
| 852 | : mOrientationHelper.getStartAfterPadding(); |
| 853 | } |
| 854 | } |
| 855 | return true; |
| 856 | } |
| 857 | return false; |
| 858 | } |
| 859 | |
| 860 | /** |
| 861 | * If there is a pending scroll position or saved states, updates the anchor info from that |
| 862 | * data and returns true |
| 863 | */ |
| 864 | private boolean updateAnchorFromPendingData(RecyclerView.State state, AnchorInfo anchorInfo) { |
| 865 | if (state.isPreLayout() || mPendingScrollPosition == RecyclerView.NO_POSITION) { |
| 866 | return false; |
| 867 | } |
| 868 | // validate scroll position |
| 869 | if (mPendingScrollPosition < 0 || mPendingScrollPosition >= state.getItemCount()) { |
| 870 | mPendingScrollPosition = RecyclerView.NO_POSITION; |
| 871 | mPendingScrollPositionOffset = INVALID_OFFSET; |
| 872 | if (DEBUG) { |
| 873 | Log.e(TAG, "ignoring invalid scroll position " + mPendingScrollPosition); |
| 874 | } |
| 875 | return false; |
| 876 | } |
| 877 | |
| 878 | // if child is visible, try to make it a reference child and ensure it is fully visible. |
| 879 | // if child is not visible, align it depending on its virtual position. |
| 880 | anchorInfo.mPosition = mPendingScrollPosition; |
| 881 | if (mPendingSavedState != null && mPendingSavedState.hasValidAnchor()) { |
| 882 | // Anchor offset depends on how that child was laid out. Here, we update it |
| 883 | // according to our current view bounds |
| 884 | anchorInfo.mLayoutFromEnd = mPendingSavedState.mAnchorLayoutFromEnd; |
| 885 | if (anchorInfo.mLayoutFromEnd) { |
| 886 | anchorInfo.mCoordinate = mOrientationHelper.getEndAfterPadding() |
| 887 | - mPendingSavedState.mAnchorOffset; |
| 888 | } else { |
| 889 | anchorInfo.mCoordinate = mOrientationHelper.getStartAfterPadding() |
| 890 | + mPendingSavedState.mAnchorOffset; |
| 891 | } |
| 892 | return true; |
| 893 | } |
| 894 | |
| 895 | if (mPendingScrollPositionOffset == INVALID_OFFSET) { |
| 896 | View child = findViewByPosition(mPendingScrollPosition); |
| 897 | if (child != null) { |
| 898 | final int childSize = mOrientationHelper.getDecoratedMeasurement(child); |
| 899 | if (childSize > mOrientationHelper.getTotalSpace()) { |
| 900 | // item does not fit. fix depending on layout direction |
| 901 | anchorInfo.assignCoordinateFromPadding(); |
| 902 | return true; |
| 903 | } |
| 904 | final int startGap = mOrientationHelper.getDecoratedStart(child) |
| 905 | - mOrientationHelper.getStartAfterPadding(); |
| 906 | if (startGap < 0) { |
| 907 | anchorInfo.mCoordinate = mOrientationHelper.getStartAfterPadding(); |
| 908 | anchorInfo.mLayoutFromEnd = false; |
| 909 | return true; |
| 910 | } |
| 911 | final int endGap = mOrientationHelper.getEndAfterPadding() |
| 912 | - mOrientationHelper.getDecoratedEnd(child); |
| 913 | if (endGap < 0) { |
| 914 | anchorInfo.mCoordinate = mOrientationHelper.getEndAfterPadding(); |
| 915 | anchorInfo.mLayoutFromEnd = true; |
| 916 | return true; |
| 917 | } |
| 918 | anchorInfo.mCoordinate = anchorInfo.mLayoutFromEnd |
| 919 | ? (mOrientationHelper.getDecoratedEnd(child) + mOrientationHelper |
| 920 | .getTotalSpaceChange()) |
| 921 | : mOrientationHelper.getDecoratedStart(child); |
| 922 | } else { // item is not visible. |
| 923 | if (getChildCount() > 0) { |
| 924 | // get position of any child, does not matter |
| 925 | int pos = getPosition(getChildAt(0)); |
| 926 | anchorInfo.mLayoutFromEnd = mPendingScrollPosition < pos |
| 927 | == mPendingScrollPositionBottom; |
| 928 | } |
| 929 | anchorInfo.assignCoordinateFromPadding(); |
| 930 | } |
| 931 | return true; |
| 932 | } |
| 933 | // override layout from end values for consistency |
| 934 | anchorInfo.mLayoutFromEnd = mPendingScrollPositionBottom; |
| 935 | // if this changes, we should update prepareForDrop as well |
| 936 | if (mPendingScrollPositionBottom) { |
| 937 | anchorInfo.mCoordinate = mOrientationHelper.getEndAfterPadding() |
| 938 | - mPendingScrollPositionOffset; |
| 939 | } else { |
| 940 | anchorInfo.mCoordinate = mOrientationHelper.getStartAfterPadding() |
| 941 | + mPendingScrollPositionOffset; |
| 942 | } |
| 943 | return true; |
| 944 | } |
| 945 | |
| 946 | /** |
| 947 | * @return The final offset amount for children |
| 948 | */ |
| 949 | private int fixLayoutEndGap(int endOffset, RecyclerView.Recycler recycler, |
| 950 | RecyclerView.State state, boolean canOffsetChildren) { |
| 951 | if (!needFixGap) { |
| 952 | return 0; |
| 953 | } |
| 954 | int gap = mOrientationHelper.getEndAfterPadding() - endOffset; |
| 955 | int fixOffset = 0; |
| 956 | if (gap > 0) { |
| 957 | fixOffset = -scrollBy(-gap, recycler, state); |
| 958 | } else { |
| 959 | return 0; // nothing to fix |
| 960 | } |
| 961 | // move offset according to scroll amount |
| 962 | endOffset += fixOffset; |
| 963 | if (canOffsetChildren) { |
| 964 | // re-calculate gap, see if we could fix it |
| 965 | gap = mOrientationHelper.getEndAfterPadding() - endOffset; |
| 966 | if (gap > 0) { |
| 967 | mOrientationHelper.offsetChildren(gap); |
| 968 | return gap + fixOffset; |
| 969 | } |
| 970 | } |
| 971 | return fixOffset; |
| 972 | } |
| 973 | |
| 974 | public int getStarForFixGap() { |
| 975 | return mOrientationHelper.getStartAfterPadding(); |
| 976 | } |
| 977 | |
| 978 | /** |
| 979 | * @return The final offset amount for children |
| 980 | */ |
| 981 | private int fixLayoutStartGap(int startOffset, RecyclerView.Recycler recycler, |
| 982 | RecyclerView.State state, boolean canOffsetChildren) { |
| 983 | if (!needFixGap) { |
| 984 | return 0; |
| 985 | } |
| 986 | int gap = startOffset - getStarForFixGap(); |
| 987 | int fixOffset = 0; |
| 988 | if (gap > 0) { |
| 989 | // check if we should fix this gap. |
| 990 | fixOffset = -scrollBy(gap, recycler, state); |
| 991 | } else { |
| 992 | return 0; // nothing to fix |
| 993 | } |
| 994 | startOffset += fixOffset; |
| 995 | if (canOffsetChildren) { |
| 996 | // re-calculate gap, see if we could fix it |
| 997 | gap = startOffset - mOrientationHelper.getStartAfterPadding(); |
| 998 | if (gap > 0) { |
| 999 | mOrientationHelper.offsetChildren(-gap); |
| 1000 | return fixOffset - gap; |
| 1001 | } |
| 1002 | } |
| 1003 | return fixOffset; |
| 1004 | } |
| 1005 | |
| 1006 | private void updateLayoutStateToFillEnd(AnchorInfo anchorInfo) { |
| 1007 | updateLayoutStateToFillEnd(anchorInfo.mPosition, anchorInfo.mCoordinate); |
| 1008 | } |
| 1009 | |
| 1010 | private void updateLayoutStateToFillEnd(int itemPosition, int offset) { |
| 1011 | mLayoutState.mAvailable = mOrientationHelper.getEndAfterPadding() - offset; |
| 1012 | mLayoutState.mItemDirection = mShouldReverseLayout ? LayoutState.ITEM_DIRECTION_HEAD : |
| 1013 | LayoutState.ITEM_DIRECTION_TAIL; |
| 1014 | mLayoutState.mCurrentPosition = itemPosition; |
| 1015 | mLayoutState.mLayoutDirection = LayoutState.LAYOUT_END; |
| 1016 | mLayoutState.mOffset = offset; |
| 1017 | mLayoutState.mScrollingOffset = LayoutState.SCROLLING_OFFSET_NaN; |
| 1018 | } |
| 1019 | |
| 1020 | private void updateLayoutStateToFillStart(AnchorInfo anchorInfo) { |
| 1021 | updateLayoutStateToFillStart(anchorInfo.mPosition, anchorInfo.mCoordinate); |
| 1022 | } |
| 1023 | |
| 1024 | private void updateLayoutStateToFillStart(int itemPosition, int offset) { |
| 1025 | mLayoutState.mAvailable = offset - mOrientationHelper.getStartAfterPadding(); |
| 1026 | mLayoutState.mCurrentPosition = itemPosition; |
| 1027 | mLayoutState.mItemDirection = mShouldReverseLayout ? LayoutState.ITEM_DIRECTION_TAIL : |
| 1028 | LayoutState.ITEM_DIRECTION_HEAD; |
| 1029 | mLayoutState.mLayoutDirection = LayoutState.LAYOUT_START; |
| 1030 | mLayoutState.mOffset = offset; |
| 1031 | mLayoutState.mScrollingOffset = LayoutState.SCROLLING_OFFSET_NaN; |
| 1032 | |
| 1033 | } |
| 1034 | |
| 1035 | protected boolean isLayoutRTL() { |
| 1036 | return getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL; |
| 1037 | } |
| 1038 | |
| 1039 | void ensureLayoutState() { |
| 1040 | if (mLayoutState == null) { |
| 1041 | mLayoutState = createLayoutState(); |
| 1042 | } |
| 1043 | } |
| 1044 | |
| 1045 | /** |
| 1046 | * Test overrides this to plug some tracking and verification. |
| 1047 | * |
| 1048 | * @return A new LayoutState |
| 1049 | */ |
| 1050 | LayoutState createLayoutState() { |
| 1051 | return new LayoutState(); |
| 1052 | } |
| 1053 | |
| 1054 | /** |
| 1055 | * <p>Scroll the RecyclerView to make the position visible.</p> |
| 1056 | * |
| 1057 | * <p>RecyclerView will scroll the minimum amount that is necessary to make the |
| 1058 | * target position visible. If you are looking for a similar behavior to |
| 1059 | * {@link android.widget.ListView#setSelection(int)} or |
| 1060 | * {@link android.widget.ListView#setSelectionFromTop(int, int)}, use |
| 1061 | * {@link #scrollToPositionWithOffset(int, int)}.</p> |
| 1062 | * |
| 1063 | * <p>Note that scroll position change will not be reflected until the next layout call.</p> |
| 1064 | * |
| 1065 | * @param position Scroll to this adapter position |
| 1066 | * @see #scrollToPositionWithOffset(int, int) |
| 1067 | */ |
| 1068 | @Override |
| 1069 | public void scrollToPosition(int position) { |
| 1070 | mPendingScrollPosition = position; |
| 1071 | mPendingScrollPositionOffset = INVALID_OFFSET; |
| 1072 | if (mPendingSavedState != null) { |
| 1073 | mPendingSavedState.invalidateAnchor(); |
| 1074 | } |
| 1075 | requestLayout(); |
| 1076 | } |
| 1077 | |
| 1078 | /** |
| 1079 | * Scroll to the specified adapter position with the given offset from resolved layout |
| 1080 | * start. Resolved layout start depends on {@link #getReverseLayout()}, |
| 1081 | * {@link ViewCompat#getLayoutDirection(android.view.View)} and {@link #getStackFromEnd()}. |
| 1082 | * <p> |
| 1083 | * For example, if layout is {@link #VERTICAL} and {@link #getStackFromEnd()} is true, calling |
| 1084 | * <code>scrollToPositionWithOffset(10, 20)</code> will layout such that |
| 1085 | * <code>item[10]</code>'s bottom is 20 pixels above the RecyclerView's bottom. |
| 1086 | * <p> |
| 1087 | * Note that scroll position change will not be reflected until the next layout call. |
| 1088 | * <p> |
| 1089 | * If you are just trying to make a position visible, use {@link #scrollToPosition(int)}. |
| 1090 | * |
| 1091 | * @param position Index (starting at 0) of the reference item. |
| 1092 | * @param offset The distance (in pixels) between the start edge of the item view and |
| 1093 | * start edge of the RecyclerView. |
| 1094 | * @see #setReverseLayout(boolean) |
| 1095 | * @see #scrollToPosition(int) |
| 1096 | */ |
| 1097 | public void scrollToPositionWithOffset(int position, int offset) { |
| 1098 | scrollToPositionWithOffset(position, offset, mShouldReverseLayout); |
| 1099 | } |
| 1100 | |
| 1101 | public void scrollToPositionWithOffset(int position, int offset, boolean bottom) { |
| 1102 | if (mPendingScrollPosition == position && mPendingScrollPositionOffset == offset && mPendingScrollPositionBottom == bottom) { |
| 1103 | return; |
| 1104 | } |
| 1105 | mPendingScrollPosition = position; |
| 1106 | mPendingScrollPositionOffset = offset; |
| 1107 | mPendingScrollPositionBottom = bottom; |
| 1108 | if (mPendingSavedState != null) { |
| 1109 | mPendingSavedState.invalidateAnchor(); |
| 1110 | } |
| 1111 | requestLayout(); |
| 1112 | } |
| 1113 | |
| 1114 | |
| 1115 | /** |
| 1116 | * {@inheritDoc} |
| 1117 | */ |
| 1118 | @Override |
| 1119 | public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, |
| 1120 | RecyclerView.State state) { |
| 1121 | if (mOrientation == VERTICAL) { |
| 1122 | return 0; |
| 1123 | } |
| 1124 | return scrollBy(dx, recycler, state); |
| 1125 | } |
| 1126 | |
| 1127 | /** |
| 1128 | * {@inheritDoc} |
| 1129 | */ |
| 1130 | @Override |
| 1131 | public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, |
| 1132 | RecyclerView.State state) { |
| 1133 | if (mOrientation == HORIZONTAL) { |
| 1134 | return 0; |
| 1135 | } |
| 1136 | return scrollBy(dy, recycler, state); |
| 1137 | } |
| 1138 | |
| 1139 | @Override |
| 1140 | public int computeHorizontalScrollOffset(RecyclerView.State state) { |
| 1141 | return computeScrollOffset(state); |
| 1142 | } |
| 1143 | |
| 1144 | @Override |
| 1145 | public int computeVerticalScrollOffset(RecyclerView.State state) { |
| 1146 | return computeScrollOffset(state); |
| 1147 | } |
| 1148 | |
| 1149 | @Override |
| 1150 | public int computeHorizontalScrollExtent(RecyclerView.State state) { |
| 1151 | return computeScrollExtent(state); |
| 1152 | } |
| 1153 | |
| 1154 | @Override |
| 1155 | public int computeVerticalScrollExtent(RecyclerView.State state) { |
| 1156 | return computeScrollExtent(state); |
| 1157 | } |
| 1158 | |
| 1159 | @Override |
| 1160 | public int computeHorizontalScrollRange(RecyclerView.State state) { |
| 1161 | return computeScrollRange(state); |
| 1162 | } |
| 1163 | |
| 1164 | @Override |
| 1165 | public int computeVerticalScrollRange(RecyclerView.State state) { |
| 1166 | return computeScrollRange(state); |
| 1167 | } |
| 1168 | |
| 1169 | private int computeScrollOffset(RecyclerView.State state) { |
| 1170 | if (getChildCount() == 0) { |
| 1171 | return 0; |
| 1172 | } |
| 1173 | ensureLayoutState(); |
| 1174 | return ScrollbarHelper.computeScrollOffset(state, mOrientationHelper, |
| 1175 | findFirstVisibleChildClosestToStart(!mSmoothScrollbarEnabled, true), |
| 1176 | findFirstVisibleChildClosestToEnd(!mSmoothScrollbarEnabled, true), |
| 1177 | this, mSmoothScrollbarEnabled, mShouldReverseLayout); |
| 1178 | } |
| 1179 | |
| 1180 | private int computeScrollExtent(RecyclerView.State state) { |
| 1181 | if (getChildCount() == 0) { |
| 1182 | return 0; |
| 1183 | } |
| 1184 | ensureLayoutState(); |
| 1185 | return ScrollbarHelper.computeScrollExtent(state, mOrientationHelper, |
| 1186 | findFirstVisibleChildClosestToStart(!mSmoothScrollbarEnabled, true), |
| 1187 | findFirstVisibleChildClosestToEnd(!mSmoothScrollbarEnabled, true), |
| 1188 | this, mSmoothScrollbarEnabled); |
| 1189 | } |
| 1190 | |
| 1191 | private int computeScrollRange(RecyclerView.State state) { |
| 1192 | if (getChildCount() == 0) { |
| 1193 | return 0; |
| 1194 | } |
| 1195 | ensureLayoutState(); |
| 1196 | return ScrollbarHelper.computeScrollRange(state, mOrientationHelper, |
| 1197 | findFirstVisibleChildClosestToStart(!mSmoothScrollbarEnabled, true), |
| 1198 | findFirstVisibleChildClosestToEnd(!mSmoothScrollbarEnabled, true), |
| 1199 | this, mSmoothScrollbarEnabled); |
| 1200 | } |
| 1201 | |
| 1202 | /** |
| 1203 | * When smooth scrollbar is enabled, the position and size of the scrollbar thumb is computed |
| 1204 | * based on the number of visible pixels in the visible items. This however assumes that all |
| 1205 | * list items have similar or equal widths or heights (depending on list orientation). |
| 1206 | * If you use a list in which items have different dimensions, the scrollbar will change |
| 1207 | * appearance as the user scrolls through the list. To avoid this issue, you need to disable |
| 1208 | * this property. |
| 1209 | * |
| 1210 | * When smooth scrollbar is disabled, the position and size of the scrollbar thumb is based |
| 1211 | * solely on the number of items in the adapter and the position of the visible items inside |
| 1212 | * the adapter. This provides a stable scrollbar as the user navigates through a list of items |
| 1213 | * with varying widths / heights. |
| 1214 | * |
| 1215 | * @param enabled Whether or not to enable smooth scrollbar. |
| 1216 | * |
| 1217 | * @see #setSmoothScrollbarEnabled(boolean) |
| 1218 | */ |
| 1219 | public void setSmoothScrollbarEnabled(boolean enabled) { |
| 1220 | mSmoothScrollbarEnabled = enabled; |
| 1221 | } |
| 1222 | |
| 1223 | /** |
| 1224 | * Returns the current state of the smooth scrollbar feature. It is enabled by default. |
| 1225 | * |
| 1226 | * @return True if smooth scrollbar is enabled, false otherwise. |
| 1227 | * |
| 1228 | * @see #setSmoothScrollbarEnabled(boolean) |
| 1229 | */ |
| 1230 | public boolean isSmoothScrollbarEnabled() { |
| 1231 | return mSmoothScrollbarEnabled; |
| 1232 | } |
| 1233 | |
| 1234 | private void updateLayoutState(int layoutDirection, int requiredSpace, |
| 1235 | boolean canUseExistingSpace, RecyclerView.State state) { |
| 1236 | // If parent provides a hint, don't measure unlimited. |
| 1237 | mLayoutState.mInfinite = resolveIsInfinite(); |
| 1238 | mLayoutState.mLayoutDirection = layoutDirection; |
| 1239 | mReusableIntPair[0] = 0; |
| 1240 | mReusableIntPair[1] = 0; |
| 1241 | calculateExtraLayoutSpace(state, mReusableIntPair); |
| 1242 | int extraForStart = Math.max(0, mReusableIntPair[0]); |
| 1243 | int extraForEnd = Math.max(0, mReusableIntPair[1]); |
| 1244 | boolean layoutToEnd = layoutDirection == LayoutState.LAYOUT_END; |
| 1245 | mLayoutState.mExtraFillSpace = layoutToEnd ? extraForEnd : extraForStart; |
| 1246 | mLayoutState.mNoRecycleSpace = layoutToEnd ? extraForStart : extraForEnd; |
| 1247 | int scrollingOffset; |
| 1248 | if (layoutToEnd) { |
| 1249 | mLayoutState.mExtraFillSpace += mOrientationHelper.getEndPadding(); |
| 1250 | // get the first child in the direction we are going |
| 1251 | final View child = getChildClosestToEnd(); |
| 1252 | // the direction in which we are traversing children |
| 1253 | mLayoutState.mItemDirection = mShouldReverseLayout ? LayoutState.ITEM_DIRECTION_HEAD |
| 1254 | : LayoutState.ITEM_DIRECTION_TAIL; |
| 1255 | mLayoutState.mCurrentPosition = getPosition(child) + mLayoutState.mItemDirection; |
| 1256 | mLayoutState.mOffset = mOrientationHelper.getDecoratedEnd(child); |
| 1257 | // calculate how much we can scroll without adding new children (independent of layout) |
| 1258 | scrollingOffset = mOrientationHelper.getDecoratedEnd(child) |
| 1259 | - mOrientationHelper.getEndAfterPadding(); |
| 1260 | |
| 1261 | } else { |
| 1262 | final View child = getChildClosestToStart(); |
| 1263 | mLayoutState.mExtraFillSpace += mOrientationHelper.getStartAfterPadding(); |
| 1264 | mLayoutState.mItemDirection = mShouldReverseLayout ? LayoutState.ITEM_DIRECTION_TAIL |
| 1265 | : LayoutState.ITEM_DIRECTION_HEAD; |
| 1266 | mLayoutState.mCurrentPosition = getPosition(child) + mLayoutState.mItemDirection; |
| 1267 | mLayoutState.mOffset = mOrientationHelper.getDecoratedStart(child); |
| 1268 | scrollingOffset = -mOrientationHelper.getDecoratedStart(child) |
| 1269 | + mOrientationHelper.getStartAfterPadding(); |
| 1270 | } |
| 1271 | mLayoutState.mAvailable = requiredSpace; |
| 1272 | if (canUseExistingSpace) { |
| 1273 | mLayoutState.mAvailable -= scrollingOffset; |
| 1274 | } |
| 1275 | mLayoutState.mScrollingOffset = scrollingOffset; |
| 1276 | } |
| 1277 | |
| 1278 | boolean resolveIsInfinite() { |
| 1279 | return mOrientationHelper.getMode() == View.MeasureSpec.UNSPECIFIED |
| 1280 | && mOrientationHelper.getEnd() == 0; |
| 1281 | } |
| 1282 | |
| 1283 | void collectPrefetchPositionsForLayoutState(RecyclerView.State state, LayoutState layoutState, |
| 1284 | LayoutPrefetchRegistry layoutPrefetchRegistry) { |
| 1285 | final int pos = layoutState.mCurrentPosition; |
| 1286 | if (pos >= 0 && pos < state.getItemCount()) { |
| 1287 | layoutPrefetchRegistry.addPosition(pos, Math.max(0, layoutState.mScrollingOffset)); |
| 1288 | } |
| 1289 | } |
| 1290 | |
| 1291 | @Override |
| 1292 | public void collectInitialPrefetchPositions(int adapterItemCount, |
| 1293 | LayoutPrefetchRegistry layoutPrefetchRegistry) { |
| 1294 | final boolean fromEnd; |
| 1295 | final int anchorPos; |
| 1296 | if (mPendingSavedState != null && mPendingSavedState.hasValidAnchor()) { |
| 1297 | // use restored state, since it hasn't been resolved yet |
| 1298 | fromEnd = mPendingSavedState.mAnchorLayoutFromEnd; |
| 1299 | anchorPos = mPendingSavedState.mAnchorPosition; |
| 1300 | } else { |
| 1301 | resolveShouldLayoutReverse(); |
| 1302 | fromEnd = mShouldReverseLayout; |
| 1303 | if (mPendingScrollPosition == RecyclerView.NO_POSITION) { |
| 1304 | anchorPos = fromEnd ? adapterItemCount - 1 : 0; |
| 1305 | } else { |
| 1306 | anchorPos = mPendingScrollPosition; |
| 1307 | } |
| 1308 | } |
| 1309 | |
| 1310 | final int direction = fromEnd |
| 1311 | ? LayoutState.ITEM_DIRECTION_HEAD |
| 1312 | : LayoutState.ITEM_DIRECTION_TAIL; |
| 1313 | int targetPos = anchorPos; |
| 1314 | for (int i = 0; i < mInitialPrefetchItemCount; i++) { |
| 1315 | if (targetPos >= 0 && targetPos < adapterItemCount) { |
| 1316 | layoutPrefetchRegistry.addPosition(targetPos, 0); |
| 1317 | } else { |
| 1318 | break; // no more to prefetch |
| 1319 | } |
| 1320 | targetPos += direction; |
| 1321 | } |
| 1322 | } |
| 1323 | |
| 1324 | /** |
| 1325 | * Sets the number of items to prefetch in |
| 1326 | * {@link #collectInitialPrefetchPositions(int, LayoutPrefetchRegistry)}, which defines |
| 1327 | * how many inner items should be prefetched when this LayoutManager's RecyclerView |
| 1328 | * is nested inside another RecyclerView. |
| 1329 | * |
| 1330 | * <p>Set this value to the number of items this inner LayoutManager will display when it is |
| 1331 | * first scrolled into the viewport. RecyclerView will attempt to prefetch that number of items |
| 1332 | * so they are ready, avoiding jank as the inner RecyclerView is scrolled into the viewport.</p> |
| 1333 | * |
| 1334 | * <p>For example, take a vertically scrolling RecyclerView with horizontally scrolling inner |
| 1335 | * RecyclerViews. The rows always have 4 items visible in them (or 5 if not aligned). Passing |
| 1336 | * <code>4</code> to this method for each inner RecyclerView's LinearLayoutManager will enable |
| 1337 | * RecyclerView's prefetching feature to do create/bind work for 4 views within a row early, |
| 1338 | * before it is scrolled on screen, instead of just the default 2.</p> |
| 1339 | * |
| 1340 | * <p>Calling this method does nothing unless the LayoutManager is in a RecyclerView |
| 1341 | * nested in another RecyclerView.</p> |
| 1342 | * |
| 1343 | * <p class="note"><strong>Note:</strong> Setting this value to be larger than the number of |
| 1344 | * views that will be visible in this view can incur unnecessary bind work, and an increase to |
| 1345 | * the number of Views created and in active use.</p> |
| 1346 | * |
| 1347 | * @param itemCount Number of items to prefetch |
| 1348 | * |
| 1349 | * @see #isItemPrefetchEnabled() |
| 1350 | * @see #getInitialPrefetchItemCount() |
| 1351 | * @see #collectInitialPrefetchPositions(int, LayoutPrefetchRegistry) |
| 1352 | */ |
| 1353 | public void setInitialPrefetchItemCount(int itemCount) { |
| 1354 | mInitialPrefetchItemCount = itemCount; |
| 1355 | } |
| 1356 | |
| 1357 | /** |
| 1358 | * Gets the number of items to prefetch in |
| 1359 | * {@link #collectInitialPrefetchPositions(int, LayoutPrefetchRegistry)}, which defines |
| 1360 | * how many inner items should be prefetched when this LayoutManager's RecyclerView |
| 1361 | * is nested inside another RecyclerView. |
| 1362 | * |
| 1363 | * @see #isItemPrefetchEnabled() |
| 1364 | * @see #setInitialPrefetchItemCount(int) |
| 1365 | * @see #collectInitialPrefetchPositions(int, LayoutPrefetchRegistry) |
| 1366 | * |
| 1367 | * @return number of items to prefetch. |
| 1368 | */ |
| 1369 | public int getInitialPrefetchItemCount() { |
| 1370 | return mInitialPrefetchItemCount; |
| 1371 | } |
| 1372 | |
| 1373 | @Override |
| 1374 | public void collectAdjacentPrefetchPositions(int dx, int dy, RecyclerView.State state, |
| 1375 | LayoutPrefetchRegistry layoutPrefetchRegistry) { |
| 1376 | int delta = (mOrientation == HORIZONTAL) ? dx : dy; |
| 1377 | if (getChildCount() == 0 || delta == 0) { |
| 1378 | // can't support this scroll, so don't bother prefetching |
| 1379 | return; |
| 1380 | } |
| 1381 | |
| 1382 | ensureLayoutState(); |
| 1383 | final int layoutDirection = delta > 0 ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START; |
| 1384 | final int absDelta = Math.abs(delta); |
| 1385 | updateLayoutState(layoutDirection, absDelta, true, state); |
| 1386 | collectPrefetchPositionsForLayoutState(state, mLayoutState, layoutPrefetchRegistry); |
| 1387 | } |
| 1388 | |
| 1389 | int scrollBy(int delta, RecyclerView.Recycler recycler, RecyclerView.State state) { |
| 1390 | if (getChildCount() == 0 || delta == 0) { |
| 1391 | return 0; |
| 1392 | } |
| 1393 | ensureLayoutState(); |
| 1394 | mLayoutState.mRecycle = true; |
| 1395 | final int layoutDirection = delta > 0 ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START; |
| 1396 | final int absDelta = Math.abs(delta); |
| 1397 | updateLayoutState(layoutDirection, absDelta, true, state); |
| 1398 | final int consumed = mLayoutState.mScrollingOffset |
| 1399 | + fill(recycler, mLayoutState, state, false); |
| 1400 | if (consumed < 0) { |
| 1401 | if (DEBUG) { |
| 1402 | Log.d(TAG, "Don't have any more elements to scroll"); |
| 1403 | } |
| 1404 | return 0; |
| 1405 | } |
| 1406 | final int scrolled = absDelta > consumed ? layoutDirection * consumed : delta; |
| 1407 | mOrientationHelper.offsetChildren(-scrolled); |
| 1408 | mLayoutState.mLastScrollDelta = scrolled; |
| 1409 | return scrolled; |
| 1410 | } |
| 1411 | |
| 1412 | @Override |
| 1413 | public void assertNotInLayoutOrScroll(String message) { |
| 1414 | if (mPendingSavedState == null) { |
| 1415 | super.assertNotInLayoutOrScroll(message); |
| 1416 | } |
| 1417 | } |
| 1418 | |
| 1419 | /** |
| 1420 | * Recycles children between given indices. |
| 1421 | * |
| 1422 | * @param startIndex inclusive |
| 1423 | * @param endIndex exclusive |
| 1424 | */ |
| 1425 | protected void recycleChildren(RecyclerView.Recycler recycler, int startIndex, int endIndex) { |
| 1426 | if (startIndex == endIndex) { |
| 1427 | return; |
| 1428 | } |
| 1429 | if (DEBUG) { |
| 1430 | Log.d(TAG, "Recycling " + Math.abs(startIndex - endIndex) + " items"); |
| 1431 | } |
| 1432 | if (endIndex > startIndex) { |
| 1433 | for (int i = endIndex - 1; i >= startIndex; i--) { |
| 1434 | removeAndRecycleViewAt(i, recycler); |
| 1435 | } |
| 1436 | } else { |
| 1437 | for (int i = startIndex; i > endIndex; i--) { |
| 1438 | removeAndRecycleViewAt(i, recycler); |
| 1439 | } |
| 1440 | } |
| 1441 | } |
| 1442 | |
| 1443 | /** |
| 1444 | * Recycles views that went out of bounds after scrolling towards the end of the layout. |
| 1445 | * <p> |
| 1446 | * Checks both layout position and visible position to guarantee that the view is not visible. |
| 1447 | * |
| 1448 | * @param recycler Recycler instance of {@link RecyclerView} |
| 1449 | * @param scrollingOffset This can be used to add additional padding to the visible area. This |
| 1450 | * is used to detect children that will go out of bounds after scrolling, |
| 1451 | * without actually moving them. |
| 1452 | * @param noRecycleSpace Extra space that should be excluded from recycling. This is the space |
| 1453 | * from {@code extraLayoutSpace[0]}, calculated in {@link |
| 1454 | * #calculateExtraLayoutSpace}. |
| 1455 | */ |
| 1456 | protected void recycleViewsFromStart(RecyclerView.Recycler recycler, int scrollingOffset, |
| 1457 | int noRecycleSpace) { |
| 1458 | if (scrollingOffset < 0) { |
| 1459 | if (DEBUG) { |
| 1460 | Log.d(TAG, "Called recycle from start with a negative value. This might happen" |
| 1461 | + " during layout changes but may be sign of a bug"); |
| 1462 | } |
| 1463 | return; |
| 1464 | } |
| 1465 | // ignore padding, ViewGroup may not clip children. |
| 1466 | final int limit = scrollingOffset - noRecycleSpace; |
| 1467 | final int childCount = getChildCount(); |
| 1468 | if (mShouldReverseLayout) { |
| 1469 | for (int i = childCount - 1; i >= 0; i--) { |
| 1470 | View child = getChildAt(i); |
| 1471 | if (child != null) { |
| 1472 | RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(child); |
| 1473 | if (holder == null || holder.shouldIgnore()) { |
| 1474 | continue; |
| 1475 | } |
| 1476 | if (mOrientationHelper.getDecoratedEnd(child) > limit |
| 1477 | || mOrientationHelper.getTransformedEndWithDecoration(child) > limit) { |
| 1478 | // stop here |
| 1479 | recycleChildren(recycler, childCount - 1, i); |
| 1480 | return; |
| 1481 | } |
| 1482 | } |
| 1483 | } |
| 1484 | } else { |
| 1485 | for (int i = 0; i < childCount; i++) { |
| 1486 | View child = getChildAt(i); |
| 1487 | if (child != null) { |
| 1488 | RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(child); |
| 1489 | if (holder == null || holder.shouldIgnore()) { |
| 1490 | continue; |
| 1491 | } |
| 1492 | if (mOrientationHelper.getDecoratedEnd(child) > limit |
| 1493 | || mOrientationHelper.getTransformedEndWithDecoration(child) > limit) { |
| 1494 | // stop here |
| 1495 | recycleChildren(recycler, 0, i); |
| 1496 | return; |
| 1497 | } |
| 1498 | } |
| 1499 | } |
| 1500 | } |
| 1501 | } |
| 1502 | |
| 1503 | |
| 1504 | /** |
| 1505 | * Recycles views that went out of bounds after scrolling towards the start of the layout. |
| 1506 | * <p> |
| 1507 | * Checks both layout position and visible position to guarantee that the view is not visible. |
| 1508 | * |
| 1509 | * @param recycler Recycler instance of {@link RecyclerView} |
| 1510 | * @param scrollingOffset This can be used to add additional padding to the visible area. This |
| 1511 | * is used to detect children that will go out of bounds after scrolling, |
| 1512 | * without actually moving them. |
| 1513 | * @param noRecycleSpace Extra space that should be excluded from recycling. This is the space |
| 1514 | * from {@code extraLayoutSpace[1]}, calculated in {@link |
| 1515 | * #calculateExtraLayoutSpace}. |
| 1516 | */ |
| 1517 | private void recycleViewsFromEnd(RecyclerView.Recycler recycler, int scrollingOffset, |
| 1518 | int noRecycleSpace) { |
| 1519 | final int childCount = getChildCount(); |
| 1520 | if (scrollingOffset < 0) { |
| 1521 | if (DEBUG) { |
| 1522 | Log.d(TAG, "Called recycle from end with a negative value. This might happen" |
| 1523 | + " during layout changes but may be sign of a bug"); |
| 1524 | } |
| 1525 | return; |
| 1526 | } |
| 1527 | final int limit = mOrientationHelper.getEnd() - scrollingOffset + noRecycleSpace; |
| 1528 | if (mShouldReverseLayout) { |
| 1529 | for (int i = 0; i < childCount; i++) { |
| 1530 | View child = getChildAt(i); |
| 1531 | if (child != null) { |
| 1532 | RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(child); |
| 1533 | if (holder == null || holder.shouldIgnore()) { |
| 1534 | continue; |
| 1535 | } |
| 1536 | if (mOrientationHelper.getDecoratedStart(child) < limit |
| 1537 | || mOrientationHelper.getTransformedStartWithDecoration(child) < limit) { |
| 1538 | // stop here |
| 1539 | recycleChildren(recycler, 0, i); |
| 1540 | return; |
| 1541 | } |
| 1542 | } |
| 1543 | } |
| 1544 | } else { |
| 1545 | for (int i = childCount - 1; i >= 0; i--) { |
| 1546 | View child = getChildAt(i); |
| 1547 | if (child != null) { |
| 1548 | RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(child); |
| 1549 | if (holder == null || holder.shouldIgnore()) { |
| 1550 | continue; |
| 1551 | } |
| 1552 | if (mOrientationHelper.getDecoratedStart(child) < limit |
| 1553 | || mOrientationHelper.getTransformedStartWithDecoration(child) < limit) { |
| 1554 | // stop here |
| 1555 | recycleChildren(recycler, childCount - 1, i); |
| 1556 | return; |
| 1557 | } |
| 1558 | } |
| 1559 | } |
| 1560 | } |
| 1561 | } |
| 1562 | |
| 1563 | /** |
| 1564 | * Helper method to call appropriate recycle method depending on current layout direction |
| 1565 | * |
| 1566 | * @param recycler Current recycler that is attached to RecyclerView |
| 1567 | * @param layoutState Current layout state. Right now, this object does not change but |
| 1568 | * we may consider moving it out of this view so passing around as a |
| 1569 | * parameter for now, rather than accessing {@link #mLayoutState} |
| 1570 | * @see #recycleViewsFromStart(RecyclerView.Recycler, int, int) |
| 1571 | * @see #recycleViewsFromEnd(RecyclerView.Recycler, int, int) |
| 1572 | * @see LinearLayoutManager.LayoutState#mLayoutDirection |
| 1573 | */ |
| 1574 | private void recycleByLayoutState(RecyclerView.Recycler recycler, LayoutState layoutState) { |
| 1575 | if (!layoutState.mRecycle || layoutState.mInfinite) { |
| 1576 | return; |
| 1577 | } |
| 1578 | int scrollingOffset = layoutState.mScrollingOffset; |
| 1579 | int noRecycleSpace = layoutState.mNoRecycleSpace; |
| 1580 | if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) { |
| 1581 | recycleViewsFromEnd(recycler, scrollingOffset, noRecycleSpace); |
| 1582 | } else { |
| 1583 | recycleViewsFromStart(recycler, scrollingOffset, noRecycleSpace); |
| 1584 | } |
| 1585 | } |
| 1586 | |
| 1587 | /** |
| 1588 | * The magic functions :). Fills the given layout, defined by the layoutState. This is fairly |
| 1589 | * independent from the rest of the {@link LinearLayoutManager} |
| 1590 | * and with little change, can be made publicly available as a helper class. |
| 1591 | * |
| 1592 | * @param recycler Current recycler that is attached to RecyclerView |
| 1593 | * @param layoutState Configuration on how we should fill out the available space. |
| 1594 | * @param state Context passed by the RecyclerView to control scroll steps. |
| 1595 | * @param stopOnFocusable If true, filling stops in the first focusable new child |
| 1596 | * @return Number of pixels that it added. Useful for scroll functions. |
| 1597 | */ |
| 1598 | int fill(RecyclerView.Recycler recycler, LayoutState layoutState, |
| 1599 | RecyclerView.State state, boolean stopOnFocusable) { |
| 1600 | // max offset we should set is mFastScroll + available |
| 1601 | final int start = layoutState.mAvailable; |
| 1602 | if (layoutState.mScrollingOffset != LayoutState.SCROLLING_OFFSET_NaN) { |
| 1603 | // TODO ugly bug fix. should not happen |
| 1604 | if (layoutState.mAvailable < 0) { |
| 1605 | layoutState.mScrollingOffset += layoutState.mAvailable; |
| 1606 | } |
| 1607 | recycleByLayoutState(recycler, layoutState); |
| 1608 | } |
| 1609 | int remainingSpace = layoutState.mAvailable + layoutState.mExtraFillSpace; |
| 1610 | LayoutChunkResult layoutChunkResult = mLayoutChunkResult; |
| 1611 | while ((layoutState.mInfinite || remainingSpace > 0) && layoutState.hasMore(state)) { |
| 1612 | layoutChunkResult.resetInternal(); |
| 1613 | if (RecyclerView.VERBOSE_TRACING) { |
| 1614 | TraceCompat.beginSection("LLM LayoutChunk"); |
| 1615 | } |
| 1616 | layoutChunk(recycler, state, layoutState, layoutChunkResult); |
| 1617 | if (RecyclerView.VERBOSE_TRACING) { |
| 1618 | TraceCompat.endSection(); |
| 1619 | } |
| 1620 | if (layoutChunkResult.mFinished) { |
| 1621 | break; |
| 1622 | } |
| 1623 | layoutState.mOffset += layoutChunkResult.mConsumed * layoutState.mLayoutDirection; |
| 1624 | /** |
| 1625 | * Consume the available space if: |
| 1626 | * * layoutChunk did not request to be ignored |
| 1627 | * * OR we are laying out scrap children |
| 1628 | * * OR we are not doing pre-layout |
| 1629 | */ |
| 1630 | if (!layoutChunkResult.mIgnoreConsumed || layoutState.mScrapList != null |
| 1631 | || !state.isPreLayout()) { |
| 1632 | layoutState.mAvailable -= layoutChunkResult.mConsumed; |
| 1633 | // we keep a separate remaining space because mAvailable is important for recycling |
| 1634 | remainingSpace -= layoutChunkResult.mConsumed; |
| 1635 | } |
| 1636 | |
| 1637 | if (layoutState.mScrollingOffset != LayoutState.SCROLLING_OFFSET_NaN) { |
| 1638 | layoutState.mScrollingOffset += layoutChunkResult.mConsumed; |
| 1639 | if (layoutState.mAvailable < 0) { |
| 1640 | layoutState.mScrollingOffset += layoutState.mAvailable; |
| 1641 | } |
| 1642 | recycleByLayoutState(recycler, layoutState); |
| 1643 | } |
| 1644 | if (stopOnFocusable && layoutChunkResult.mFocusable) { |
| 1645 | break; |
| 1646 | } |
| 1647 | } |
| 1648 | // if (DEBUG) { |
| 1649 | // validateChildOrder(); |
| 1650 | // } |
| 1651 | return start - layoutState.mAvailable; |
| 1652 | } |
| 1653 | |
| 1654 | void layoutChunk(RecyclerView.Recycler recycler, RecyclerView.State state, |
| 1655 | LayoutState layoutState, LayoutChunkResult result) { |
| 1656 | View view = layoutState.next(recycler); |
| 1657 | if (view == null) { |
| 1658 | if (DEBUG && layoutState.mScrapList == null) { |
| 1659 | throw new RuntimeException("received null view when unexpected"); |
| 1660 | } |
| 1661 | // if we are laying out views in scrap, this may return null which means there is |
| 1662 | // no more items to layout. |
| 1663 | result.mFinished = true; |
| 1664 | return; |
| 1665 | } |
| 1666 | RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams(); |
| 1667 | if (layoutState.mScrapList == null) { |
| 1668 | if (mShouldReverseLayout == (layoutState.mLayoutDirection |
| 1669 | == LayoutState.LAYOUT_START)) { |
| 1670 | addView(view); |
| 1671 | } else { |
| 1672 | addView(view, 0); |
| 1673 | } |
| 1674 | } else { |
| 1675 | if (mShouldReverseLayout == (layoutState.mLayoutDirection |
| 1676 | == LayoutState.LAYOUT_START)) { |
| 1677 | addDisappearingView(view); |
| 1678 | } else { |
| 1679 | addDisappearingView(view, 0); |
| 1680 | } |
| 1681 | } |
| 1682 | measureChildWithMargins(view, 0, 0); |
| 1683 | result.mConsumed = mOrientationHelper.getDecoratedMeasurement(view); |
| 1684 | int left, top, right, bottom; |
| 1685 | if (mOrientation == VERTICAL) { |
| 1686 | if (isLayoutRTL()) { |
| 1687 | right = getWidth() - getPaddingRight(); |
| 1688 | left = right - mOrientationHelper.getDecoratedMeasurementInOther(view); |
| 1689 | } else { |
| 1690 | left = getPaddingLeft(); |
| 1691 | right = left + mOrientationHelper.getDecoratedMeasurementInOther(view); |
| 1692 | } |
| 1693 | if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) { |
| 1694 | bottom = layoutState.mOffset; |
| 1695 | top = layoutState.mOffset - result.mConsumed; |
| 1696 | } else { |
| 1697 | top = layoutState.mOffset; |
| 1698 | bottom = layoutState.mOffset + result.mConsumed; |
| 1699 | } |
| 1700 | } else { |
| 1701 | top = getPaddingTop(); |
| 1702 | bottom = top + mOrientationHelper.getDecoratedMeasurementInOther(view); |
| 1703 | |
| 1704 | if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) { |
| 1705 | right = layoutState.mOffset; |
| 1706 | left = layoutState.mOffset - result.mConsumed; |
| 1707 | } else { |
| 1708 | left = layoutState.mOffset; |
| 1709 | right = layoutState.mOffset + result.mConsumed; |
| 1710 | } |
| 1711 | } |
| 1712 | // We calculate everything with View's bounding box (which includes decor and margins) |
| 1713 | // To calculate correct layout position, we subtract margins. |
| 1714 | layoutDecoratedWithMargins(view, left, top, right, bottom); |
| 1715 | if (DEBUG) { |
| 1716 | Log.d(TAG, "laid out child at position " + getPosition(view) + ", with l:" |
| 1717 | + (left + params.leftMargin) + ", t:" + (top + params.topMargin) + ", r:" |
| 1718 | + (right - params.rightMargin) + ", b:" + (bottom - params.bottomMargin)); |
| 1719 | } |
| 1720 | // Consume the available space if the view is not removed OR changed |
| 1721 | if (params.isItemRemoved() || params.isItemChanged()) { |
| 1722 | result.mIgnoreConsumed = true; |
| 1723 | } |
| 1724 | result.mFocusable = view.hasFocusable(); |
| 1725 | } |
| 1726 | |
| 1727 | @Override |
| 1728 | boolean shouldMeasureTwice() { |
| 1729 | return getHeightMode() != View.MeasureSpec.EXACTLY |
| 1730 | && getWidthMode() != View.MeasureSpec.EXACTLY |
| 1731 | && hasFlexibleChildInBothOrientations(); |
| 1732 | } |
| 1733 | |
| 1734 | /** |
| 1735 | * Converts a focusDirection to orientation. |
| 1736 | * |
| 1737 | * @param focusDirection One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, |
| 1738 | * {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT}, |
| 1739 | * {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD} |
| 1740 | * or 0 for not applicable |
| 1741 | * @return {@link LayoutState#LAYOUT_START} or {@link LayoutState#LAYOUT_END} if focus direction |
| 1742 | * is applicable to current state, {@link LayoutState#INVALID_LAYOUT} otherwise. |
| 1743 | */ |
| 1744 | int convertFocusDirectionToLayoutDirection(int focusDirection) { |
| 1745 | switch (focusDirection) { |
| 1746 | case View.FOCUS_BACKWARD: |
| 1747 | if (mOrientation == VERTICAL) { |
| 1748 | return LayoutState.LAYOUT_START; |
| 1749 | } else if (isLayoutRTL()) { |
| 1750 | return LayoutState.LAYOUT_END; |
| 1751 | } else { |
| 1752 | return LayoutState.LAYOUT_START; |
| 1753 | } |
| 1754 | case View.FOCUS_FORWARD: |
| 1755 | if (mOrientation == VERTICAL) { |
| 1756 | return LayoutState.LAYOUT_END; |
| 1757 | } else if (isLayoutRTL()) { |
| 1758 | return LayoutState.LAYOUT_START; |
| 1759 | } else { |
| 1760 | return LayoutState.LAYOUT_END; |
| 1761 | } |
| 1762 | case View.FOCUS_UP: |
| 1763 | return mOrientation == VERTICAL ? LayoutState.LAYOUT_START |
| 1764 | : LayoutState.INVALID_LAYOUT; |
| 1765 | case View.FOCUS_DOWN: |
| 1766 | return mOrientation == VERTICAL ? LayoutState.LAYOUT_END |
| 1767 | : LayoutState.INVALID_LAYOUT; |
| 1768 | case View.FOCUS_LEFT: |
| 1769 | return mOrientation == HORIZONTAL ? LayoutState.LAYOUT_START |
| 1770 | : LayoutState.INVALID_LAYOUT; |
| 1771 | case View.FOCUS_RIGHT: |
| 1772 | return mOrientation == HORIZONTAL ? LayoutState.LAYOUT_END |
| 1773 | : LayoutState.INVALID_LAYOUT; |
| 1774 | default: |
| 1775 | if (DEBUG) { |
| 1776 | Log.d(TAG, "Unknown focus request:" + focusDirection); |
| 1777 | } |
| 1778 | return LayoutState.INVALID_LAYOUT; |
| 1779 | } |
| 1780 | |
| 1781 | } |
| 1782 | |
| 1783 | /** |
| 1784 | * Convenience method to find the child closes to start. Caller should check it has enough |
| 1785 | * children. |
| 1786 | * |
| 1787 | * @return The child closes to start of the layout from user's perspective. |
| 1788 | */ |
| 1789 | private View getChildClosestToStart() { |
| 1790 | return getChildAt(mShouldReverseLayout ? getChildCount() - 1 : 0); |
| 1791 | } |
| 1792 | |
| 1793 | /** |
| 1794 | * Convenience method to find the child closes to end. Caller should check it has enough |
| 1795 | * children. |
| 1796 | * |
| 1797 | * @return The child closes to end of the layout from user's perspective. |
| 1798 | */ |
| 1799 | private View getChildClosestToEnd() { |
| 1800 | return getChildAt(mShouldReverseLayout ? 0 : getChildCount() - 1); |
| 1801 | } |
| 1802 | |
| 1803 | /** |
| 1804 | * Convenience method to find the visible child closes to start. Caller should check if it has |
| 1805 | * enough children. |
| 1806 | * |
| 1807 | * @param completelyVisible Whether child should be completely visible or not |
| 1808 | * @return The first visible child closest to start of the layout from user's perspective. |
| 1809 | */ |
| 1810 | View findFirstVisibleChildClosestToStart(boolean completelyVisible, |
| 1811 | boolean acceptPartiallyVisible) { |
| 1812 | if (mShouldReverseLayout) { |
| 1813 | return findOneVisibleChild(getChildCount() - 1, -1, completelyVisible, |
| 1814 | acceptPartiallyVisible); |
| 1815 | } else { |
| 1816 | return findOneVisibleChild(0, getChildCount(), completelyVisible, |
| 1817 | acceptPartiallyVisible); |
| 1818 | } |
| 1819 | } |
| 1820 | |
| 1821 | /** |
| 1822 | * Convenience method to find the visible child closes to end. Caller should check if it has |
| 1823 | * enough children. |
| 1824 | * |
| 1825 | * @param completelyVisible Whether child should be completely visible or not |
| 1826 | * @return The first visible child closest to end of the layout from user's perspective. |
| 1827 | */ |
| 1828 | View findFirstVisibleChildClosestToEnd(boolean completelyVisible, |
| 1829 | boolean acceptPartiallyVisible) { |
| 1830 | if (mShouldReverseLayout) { |
| 1831 | return findOneVisibleChild(0, getChildCount(), completelyVisible, |
| 1832 | acceptPartiallyVisible); |
| 1833 | } else { |
| 1834 | return findOneVisibleChild(getChildCount() - 1, -1, completelyVisible, |
| 1835 | acceptPartiallyVisible); |
| 1836 | } |
| 1837 | } |
| 1838 | |
| 1839 | |
| 1840 | /** |
| 1841 | * Among the children that are suitable to be considered as an anchor child, returns the one |
| 1842 | * closest to the end of the layout. |
| 1843 | * <p> |
| 1844 | * Due to ambiguous adapter updates or children being removed, some children's positions may be |
| 1845 | * invalid. This method is a best effort to find a position within adapter bounds if possible. |
| 1846 | * <p> |
| 1847 | * It also prioritizes children that are within the visible bounds. |
| 1848 | * @return A View that can be used an an anchor View. |
| 1849 | */ |
| 1850 | private View findReferenceChildClosestToEnd(RecyclerView.Recycler recycler, |
| 1851 | RecyclerView.State state) { |
| 1852 | return mShouldReverseLayout ? findFirstReferenceChild(recycler, state) : |
| 1853 | findLastReferenceChild(recycler, state); |
| 1854 | } |
| 1855 | |
| 1856 | /** |
| 1857 | * Among the children that are suitable to be considered as an anchor child, returns the one |
| 1858 | * closest to the start of the layout. |
| 1859 | * <p> |
| 1860 | * Due to ambiguous adapter updates or children being removed, some children's positions may be |
| 1861 | * invalid. This method is a best effort to find a position within adapter bounds if possible. |
| 1862 | * <p> |
| 1863 | * It also prioritizes children that are within the visible bounds. |
| 1864 | * |
| 1865 | * @return A View that can be used an an anchor View. |
| 1866 | */ |
| 1867 | private View findReferenceChildClosestToStart(RecyclerView.Recycler recycler, |
| 1868 | RecyclerView.State state) { |
| 1869 | return mShouldReverseLayout ? findLastReferenceChild(recycler, state) : |
| 1870 | findFirstReferenceChild(recycler, state); |
| 1871 | } |
| 1872 | |
| 1873 | private View findFirstReferenceChild(RecyclerView.Recycler recycler, RecyclerView.State state) { |
| 1874 | return findReferenceChild(recycler, state, 0, getChildCount(), state.getItemCount()); |
| 1875 | } |
| 1876 | |
| 1877 | private View findLastReferenceChild(RecyclerView.Recycler recycler, RecyclerView.State state) { |
| 1878 | return findReferenceChild(recycler, state, getChildCount() - 1, -1, state.getItemCount()); |
| 1879 | } |
| 1880 | |
| 1881 | // overridden by GridLayoutManager |
| 1882 | View findReferenceChild(RecyclerView.Recycler recycler, RecyclerView.State state, |
| 1883 | int start, int end, int itemCount) { |
| 1884 | ensureLayoutState(); |
| 1885 | View invalidMatch = null; |
| 1886 | View outOfBoundsMatch = null; |
| 1887 | final int boundsStart = mIgnoreTopPadding ? 0 : mOrientationHelper.getStartAfterPadding(); |
| 1888 | final int boundsEnd = mOrientationHelper.getEndAfterPadding(); |
| 1889 | final int diff = end > start ? 1 : -1; |
| 1890 | for (int i = start; i != end; i += diff) { |
| 1891 | final View view = getChildAt(i); |
| 1892 | final int position = getPosition(view); |
| 1893 | if (position >= 0 && position < itemCount) { |
| 1894 | if (((RecyclerView.LayoutParams) view.getLayoutParams()).isItemRemoved()) { |
| 1895 | if (invalidMatch == null) { |
| 1896 | invalidMatch = view; // removed item, least preferred |
| 1897 | } |
| 1898 | } else if (mOrientationHelper.getDecoratedStart(view) >= boundsEnd |
| 1899 | || mOrientationHelper.getDecoratedEnd(view) < boundsStart) { |
| 1900 | if (outOfBoundsMatch == null) { |
| 1901 | outOfBoundsMatch = view; // item is not visible, less preferred |
| 1902 | } |
| 1903 | } else { |
| 1904 | return view; |
| 1905 | } |
| 1906 | } |
| 1907 | } |
| 1908 | return outOfBoundsMatch != null ? outOfBoundsMatch : invalidMatch; |
| 1909 | } |
| 1910 | |
| 1911 | // returns the out-of-bound child view closest to RV's end bounds. An out-of-bound child is |
| 1912 | // defined as a child that's either partially or fully invisible (outside RV's padding area). |
| 1913 | private View findPartiallyOrCompletelyInvisibleChildClosestToEnd() { |
| 1914 | return mShouldReverseLayout ? findFirstPartiallyOrCompletelyInvisibleChild() |
| 1915 | : findLastPartiallyOrCompletelyInvisibleChild(); |
| 1916 | } |
| 1917 | |
| 1918 | // returns the out-of-bound child view closest to RV's starting bounds. An out-of-bound child is |
| 1919 | // defined as a child that's either partially or fully invisible (outside RV's padding area). |
| 1920 | private View findPartiallyOrCompletelyInvisibleChildClosestToStart() { |
| 1921 | return mShouldReverseLayout ? findLastPartiallyOrCompletelyInvisibleChild() : |
| 1922 | findFirstPartiallyOrCompletelyInvisibleChild(); |
| 1923 | } |
| 1924 | |
| 1925 | private View findFirstPartiallyOrCompletelyInvisibleChild() { |
| 1926 | return findOnePartiallyOrCompletelyInvisibleChild(0, getChildCount()); |
| 1927 | } |
| 1928 | |
| 1929 | private View findLastPartiallyOrCompletelyInvisibleChild() { |
| 1930 | return findOnePartiallyOrCompletelyInvisibleChild(getChildCount() - 1, -1); |
| 1931 | } |
| 1932 | |
| 1933 | /** |
| 1934 | * Returns the adapter position of the first visible view. This position does not include |
| 1935 | * adapter changes that were dispatched after the last layout pass. |
| 1936 | * <p> |
| 1937 | * Note that, this value is not affected by layout orientation or item order traversal. |
| 1938 | * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, |
| 1939 | * not in the layout. |
| 1940 | * <p> |
| 1941 | * If RecyclerView has item decorators, they will be considered in calculations as well. |
| 1942 | * <p> |
| 1943 | * LayoutManager may pre-cache some views that are not necessarily visible. Those views |
| 1944 | * are ignored in this method. |
| 1945 | * |
| 1946 | * @return The adapter position of the first visible item or {@link RecyclerView#NO_POSITION} if |
| 1947 | * there aren't any visible items. |
| 1948 | * @see #findFirstCompletelyVisibleItemPosition() |
| 1949 | * @see #findLastVisibleItemPosition() |
| 1950 | */ |
| 1951 | public int findFirstVisibleItemPosition() { |
| 1952 | final View child = findOneVisibleChild(0, getChildCount(), false, true); |
| 1953 | return child == null ? RecyclerView.NO_POSITION : getPosition(child); |
| 1954 | } |
| 1955 | |
| 1956 | /** |
| 1957 | * Returns the adapter position of the first fully visible view. This position does not include |
| 1958 | * adapter changes that were dispatched after the last layout pass. |
| 1959 | * <p> |
| 1960 | * Note that bounds check is only performed in the current orientation. That means, if |
| 1961 | * LayoutManager is horizontal, it will only check the view's left and right edges. |
| 1962 | * |
| 1963 | * @return The adapter position of the first fully visible item or |
| 1964 | * {@link RecyclerView#NO_POSITION} if there aren't any visible items. |
| 1965 | * @see #findFirstVisibleItemPosition() |
| 1966 | * @see #findLastCompletelyVisibleItemPosition() |
| 1967 | */ |
| 1968 | public int findFirstCompletelyVisibleItemPosition() { |
| 1969 | final View child = findOneVisibleChild(0, getChildCount(), true, false); |
| 1970 | return child == null ? RecyclerView.NO_POSITION : getPosition(child); |
| 1971 | } |
| 1972 | |
| 1973 | /** |
| 1974 | * Returns the adapter position of the last visible view. This position does not include |
| 1975 | * adapter changes that were dispatched after the last layout pass. |
| 1976 | * <p> |
| 1977 | * Note that, this value is not affected by layout orientation or item order traversal. |
| 1978 | * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, |
| 1979 | * not in the layout. |
| 1980 | * <p> |
| 1981 | * If RecyclerView has item decorators, they will be considered in calculations as well. |
| 1982 | * <p> |
| 1983 | * LayoutManager may pre-cache some views that are not necessarily visible. Those views |
| 1984 | * are ignored in this method. |
| 1985 | * |
| 1986 | * @return The adapter position of the last visible view or {@link RecyclerView#NO_POSITION} if |
| 1987 | * there aren't any visible items. |
| 1988 | * @see #findLastCompletelyVisibleItemPosition() |
| 1989 | * @see #findFirstVisibleItemPosition() |
| 1990 | */ |
| 1991 | public int findLastVisibleItemPosition() { |
| 1992 | final View child = findOneVisibleChild(getChildCount() - 1, -1, false, true); |
| 1993 | return child == null ? RecyclerView.NO_POSITION : getPosition(child); |
| 1994 | } |
| 1995 | |
| 1996 | /** |
| 1997 | * Returns the adapter position of the last fully visible view. This position does not include |
| 1998 | * adapter changes that were dispatched after the last layout pass. |
| 1999 | * <p> |
| 2000 | * Note that bounds check is only performed in the current orientation. That means, if |
| 2001 | * LayoutManager is horizontal, it will only check the view's left and right edges. |
| 2002 | * |
| 2003 | * @return The adapter position of the last fully visible view or |
| 2004 | * {@link RecyclerView#NO_POSITION} if there aren't any visible items. |
| 2005 | * @see #findLastVisibleItemPosition() |
| 2006 | * @see #findFirstCompletelyVisibleItemPosition() |
| 2007 | */ |
| 2008 | public int findLastCompletelyVisibleItemPosition() { |
| 2009 | final View child = findOneVisibleChild(getChildCount() - 1, -1, true, false); |
| 2010 | return child == null ? RecyclerView.NO_POSITION : getPosition(child); |
| 2011 | } |
| 2012 | |
| 2013 | // Returns the first child that is visible in the provided index range, i.e. either partially or |
| 2014 | // fully visible depending on the arguments provided. Completely invisible children are not |
| 2015 | // acceptable by this method, but could be returned |
| 2016 | // using #findOnePartiallyOrCompletelyInvisibleChild |
| 2017 | View findOneVisibleChild(int fromIndex, int toIndex, boolean completelyVisible, |
| 2018 | boolean acceptPartiallyVisible) { |
| 2019 | ensureLayoutState(); |
| 2020 | @ViewBoundsCheck.ViewBounds int preferredBoundsFlag = 0; |
| 2021 | @ViewBoundsCheck.ViewBounds int acceptableBoundsFlag = 0; |
| 2022 | if (completelyVisible) { |
| 2023 | preferredBoundsFlag = (ViewBoundsCheck.FLAG_CVS_GT_PVS | ViewBoundsCheck.FLAG_CVS_EQ_PVS |
| 2024 | | ViewBoundsCheck.FLAG_CVE_LT_PVE | ViewBoundsCheck.FLAG_CVE_EQ_PVE); |
| 2025 | } else { |
| 2026 | preferredBoundsFlag = (ViewBoundsCheck.FLAG_CVS_LT_PVE |
| 2027 | | ViewBoundsCheck.FLAG_CVE_GT_PVS); |
| 2028 | } |
| 2029 | if (acceptPartiallyVisible) { |
| 2030 | acceptableBoundsFlag = (ViewBoundsCheck.FLAG_CVS_LT_PVE |
| 2031 | | ViewBoundsCheck.FLAG_CVE_GT_PVS); |
| 2032 | } |
| 2033 | return (mOrientation == HORIZONTAL) ? mHorizontalBoundCheck |
| 2034 | .findOneViewWithinBoundFlags(fromIndex, toIndex, preferredBoundsFlag, |
| 2035 | acceptableBoundsFlag) : mVerticalBoundCheck |
| 2036 | .findOneViewWithinBoundFlags(fromIndex, toIndex, preferredBoundsFlag, |
| 2037 | acceptableBoundsFlag); |
| 2038 | } |
| 2039 | |
| 2040 | View findOnePartiallyOrCompletelyInvisibleChild(int fromIndex, int toIndex) { |
| 2041 | ensureLayoutState(); |
| 2042 | final int next = toIndex > fromIndex ? 1 : (toIndex < fromIndex ? -1 : 0); |
| 2043 | if (next == 0) { |
| 2044 | return getChildAt(fromIndex); |
| 2045 | } |
| 2046 | @ViewBoundsCheck.ViewBounds int preferredBoundsFlag = 0; |
| 2047 | @ViewBoundsCheck.ViewBounds int acceptableBoundsFlag = 0; |
| 2048 | if (mOrientationHelper.getDecoratedStart(getChildAt(fromIndex)) |
| 2049 | < mOrientationHelper.getStartAfterPadding()) { |
| 2050 | preferredBoundsFlag = (ViewBoundsCheck.FLAG_CVS_LT_PVS | ViewBoundsCheck.FLAG_CVE_LT_PVE |
| 2051 | | ViewBoundsCheck.FLAG_CVE_GT_PVS); |
| 2052 | acceptableBoundsFlag = (ViewBoundsCheck.FLAG_CVS_LT_PVS |
| 2053 | | ViewBoundsCheck.FLAG_CVE_LT_PVE); |
| 2054 | } else { |
| 2055 | preferredBoundsFlag = (ViewBoundsCheck.FLAG_CVE_GT_PVE | ViewBoundsCheck.FLAG_CVS_GT_PVS |
| 2056 | | ViewBoundsCheck.FLAG_CVS_LT_PVE); |
| 2057 | acceptableBoundsFlag = (ViewBoundsCheck.FLAG_CVE_GT_PVE |
| 2058 | | ViewBoundsCheck.FLAG_CVS_GT_PVS); |
| 2059 | } |
| 2060 | return (mOrientation == HORIZONTAL) ? mHorizontalBoundCheck |
| 2061 | .findOneViewWithinBoundFlags(fromIndex, toIndex, preferredBoundsFlag, |
| 2062 | acceptableBoundsFlag) : mVerticalBoundCheck |
| 2063 | .findOneViewWithinBoundFlags(fromIndex, toIndex, preferredBoundsFlag, |
| 2064 | acceptableBoundsFlag); |
| 2065 | } |
| 2066 | |
| 2067 | @Override |
| 2068 | public View onFocusSearchFailed(View focused, int focusDirection, |
| 2069 | RecyclerView.Recycler recycler, RecyclerView.State state) { |
| 2070 | resolveShouldLayoutReverse(); |
| 2071 | if (getChildCount() == 0) { |
| 2072 | return null; |
| 2073 | } |
| 2074 | |
| 2075 | final int layoutDir = convertFocusDirectionToLayoutDirection(focusDirection); |
| 2076 | if (layoutDir == LayoutState.INVALID_LAYOUT) { |
| 2077 | return null; |
| 2078 | } |
| 2079 | ensureLayoutState(); |
| 2080 | final int maxScroll = (int) (MAX_SCROLL_FACTOR * mOrientationHelper.getTotalSpace()); |
| 2081 | updateLayoutState(layoutDir, maxScroll, false, state); |
| 2082 | mLayoutState.mScrollingOffset = LayoutState.SCROLLING_OFFSET_NaN; |
| 2083 | mLayoutState.mRecycle = false; |
| 2084 | fill(recycler, mLayoutState, state, true); |
| 2085 | |
| 2086 | // nextCandidate is the first child view in the layout direction that's partially |
| 2087 | // within RV's bounds, i.e. part of it is visible or it's completely invisible but still |
| 2088 | // touching RV's bounds. This will be the unfocusable candidate view to become visible onto |
| 2089 | // the screen if no focusable views are found in the given layout direction. |
| 2090 | final View nextCandidate; |
| 2091 | if (layoutDir == LayoutState.LAYOUT_START) { |
| 2092 | nextCandidate = findPartiallyOrCompletelyInvisibleChildClosestToStart(); |
| 2093 | } else { |
| 2094 | nextCandidate = findPartiallyOrCompletelyInvisibleChildClosestToEnd(); |
| 2095 | } |
| 2096 | // nextFocus is meaningful only if it refers to a focusable child, in which case it |
| 2097 | // indicates the next view to gain focus. |
| 2098 | final View nextFocus; |
| 2099 | if (layoutDir == LayoutState.LAYOUT_START) { |
| 2100 | nextFocus = getChildClosestToStart(); |
| 2101 | } else { |
| 2102 | nextFocus = getChildClosestToEnd(); |
| 2103 | } |
| 2104 | if (nextFocus.hasFocusable()) { |
| 2105 | if (nextCandidate == null) { |
| 2106 | return null; |
| 2107 | } |
| 2108 | return nextFocus; |
| 2109 | } |
| 2110 | return nextCandidate; |
| 2111 | } |
| 2112 | |
| 2113 | /** |
| 2114 | * Used for debugging. |
| 2115 | * Logs the internal representation of children to default logger. |
| 2116 | */ |
| 2117 | private void logChildren() { |
| 2118 | Log.d(TAG, "internal representation of views on the screen"); |
| 2119 | for (int i = 0; i < getChildCount(); i++) { |
| 2120 | View child = getChildAt(i); |
| 2121 | Log.d(TAG, "item " + getPosition(child) + ", coord:" |
| 2122 | + mOrientationHelper.getDecoratedStart(child)); |
| 2123 | } |
| 2124 | Log.d(TAG, "=============="); |
| 2125 | } |
| 2126 | |
| 2127 | /** |
| 2128 | * Used for debugging. |
| 2129 | * Validates that child views are laid out in correct order. This is important because rest of |
| 2130 | * the algorithm relies on this constraint. |
| 2131 | * |
| 2132 | * In default layout, child 0 should be closest to screen position 0 and last child should be |
| 2133 | * closest to position WIDTH or HEIGHT. |
| 2134 | * In reverse layout, last child should be closes to screen position 0 and first child should |
| 2135 | * be closest to position WIDTH or HEIGHT |
| 2136 | */ |
| 2137 | void validateChildOrder() { |
| 2138 | Log.d(TAG, "validating child count " + getChildCount()); |
| 2139 | if (getChildCount() < 1) { |
| 2140 | return; |
| 2141 | } |
| 2142 | int lastPos = getPosition(getChildAt(0)); |
| 2143 | int lastScreenLoc = mOrientationHelper.getDecoratedStart(getChildAt(0)); |
| 2144 | if (mShouldReverseLayout) { |
| 2145 | for (int i = 1; i < getChildCount(); i++) { |
| 2146 | View child = getChildAt(i); |
| 2147 | int pos = getPosition(child); |
| 2148 | int screenLoc = mOrientationHelper.getDecoratedStart(child); |
| 2149 | if (pos < lastPos) { |
| 2150 | logChildren(); |
| 2151 | throw new RuntimeException("detected invalid position. loc invalid? " |
| 2152 | + (screenLoc < lastScreenLoc)); |
| 2153 | } |
| 2154 | if (screenLoc > lastScreenLoc) { |
| 2155 | logChildren(); |
| 2156 | throw new RuntimeException("detected invalid location"); |
| 2157 | } |
| 2158 | } |
| 2159 | } else { |
| 2160 | for (int i = 1; i < getChildCount(); i++) { |
| 2161 | View child = getChildAt(i); |
| 2162 | int pos = getPosition(child); |
| 2163 | int screenLoc = mOrientationHelper.getDecoratedStart(child); |
| 2164 | if (pos < lastPos) { |
| 2165 | logChildren(); |
| 2166 | throw new RuntimeException("detected invalid position. loc invalid? " |
| 2167 | + (screenLoc < lastScreenLoc)); |
| 2168 | } |
| 2169 | if (screenLoc < lastScreenLoc) { |
| 2170 | logChildren(); |
| 2171 | throw new RuntimeException("detected invalid location"); |
| 2172 | } |
| 2173 | } |
| 2174 | } |
| 2175 | } |
| 2176 | |
| 2177 | @Override |
| 2178 | public boolean supportsPredictiveItemAnimations() { |
| 2179 | return mPendingSavedState == null && mLastStackFromEnd == mStackFromEnd; |
| 2180 | } |
| 2181 | |
| 2182 | /** |
| 2183 | * @hide This method should be called by ItemTouchHelper only. |
| 2184 | */ |
| 2185 | @RestrictTo(LIBRARY_GROUP_PREFIX) |
| 2186 | @Override |
| 2187 | public void prepareForDrop(@NonNull View view, @NonNull View target, int x, int y) { |
| 2188 | assertNotInLayoutOrScroll("Cannot drop a view during a scroll or layout calculation"); |
| 2189 | ensureLayoutState(); |
| 2190 | resolveShouldLayoutReverse(); |
| 2191 | final int myPos = getPosition(view); |
| 2192 | final int targetPos = getPosition(target); |
| 2193 | final int dropDirection = myPos < targetPos ? LayoutState.ITEM_DIRECTION_TAIL |
| 2194 | : LayoutState.ITEM_DIRECTION_HEAD; |
| 2195 | if (mShouldReverseLayout) { |
| 2196 | if (dropDirection == LayoutState.ITEM_DIRECTION_TAIL) { |
| 2197 | scrollToPositionWithOffset(targetPos, |
| 2198 | mOrientationHelper.getEndAfterPadding() |
| 2199 | - (mOrientationHelper.getDecoratedStart(target) |
| 2200 | + mOrientationHelper.getDecoratedMeasurement(view))); |
| 2201 | } else { |
| 2202 | scrollToPositionWithOffset(targetPos, |
| 2203 | mOrientationHelper.getEndAfterPadding() |
| 2204 | - mOrientationHelper.getDecoratedEnd(target)); |
| 2205 | } |
| 2206 | } else { |
| 2207 | if (dropDirection == LayoutState.ITEM_DIRECTION_HEAD) { |
| 2208 | scrollToPositionWithOffset(targetPos, mOrientationHelper.getDecoratedStart(target)); |
| 2209 | } else { |
| 2210 | scrollToPositionWithOffset(targetPos, |
| 2211 | mOrientationHelper.getDecoratedEnd(target) |
| 2212 | - mOrientationHelper.getDecoratedMeasurement(view)); |
| 2213 | } |
| 2214 | } |
| 2215 | } |
| 2216 | |
| 2217 | /** |
| 2218 | * Helper class that keeps temporary state while {LayoutManager} is filling out the empty |
| 2219 | * space. |
| 2220 | */ |
| 2221 | static class LayoutState { |
| 2222 | |
| 2223 | static final String TAG = "LLM#LayoutState"; |
| 2224 | |
| 2225 | static final int LAYOUT_START = -1; |
| 2226 | |
| 2227 | static final int LAYOUT_END = 1; |
| 2228 | |
| 2229 | static final int INVALID_LAYOUT = Integer.MIN_VALUE; |
| 2230 | |
| 2231 | static final int ITEM_DIRECTION_HEAD = -1; |
| 2232 | |
| 2233 | static final int ITEM_DIRECTION_TAIL = 1; |
| 2234 | |
| 2235 | static final int SCROLLING_OFFSET_NaN = Integer.MIN_VALUE; |
| 2236 | |
| 2237 | /** |
| 2238 | * We may not want to recycle children in some cases (e.g. layout) |
| 2239 | */ |
| 2240 | boolean mRecycle = true; |
| 2241 | |
| 2242 | /** |
| 2243 | * Pixel offset where layout should start |
| 2244 | */ |
| 2245 | int mOffset; |
| 2246 | |
| 2247 | /** |
| 2248 | * Number of pixels that we should fill, in the layout direction. |
| 2249 | */ |
| 2250 | int mAvailable; |
| 2251 | |
| 2252 | /** |
| 2253 | * Current position on the adapter to get the next item. |
| 2254 | */ |
| 2255 | int mCurrentPosition; |
| 2256 | |
| 2257 | /** |
| 2258 | * Defines the direction in which the data adapter is traversed. |
| 2259 | * Should be {@link #ITEM_DIRECTION_HEAD} or {@link #ITEM_DIRECTION_TAIL} |
| 2260 | */ |
| 2261 | int mItemDirection; |
| 2262 | |
| 2263 | /** |
| 2264 | * Defines the direction in which the layout is filled. |
| 2265 | * Should be {@link #LAYOUT_START} or {@link #LAYOUT_END} |
| 2266 | */ |
| 2267 | int mLayoutDirection; |
| 2268 | |
| 2269 | /** |
| 2270 | * Used when LayoutState is constructed in a scrolling state. |
| 2271 | * It should be set the amount of scrolling we can make without creating a new view. |
| 2272 | * Settings this is required for efficient view recycling. |
| 2273 | */ |
| 2274 | int mScrollingOffset; |
| 2275 | |
| 2276 | /** |
| 2277 | * Used if you want to pre-layout items that are not yet visible. |
| 2278 | * The difference with {@link #mAvailable} is that, when recycling, distance laid out for |
| 2279 | * {@link #mExtraFillSpace} is not considered to avoid recycling visible children. |
| 2280 | */ |
| 2281 | int mExtraFillSpace = 0; |
| 2282 | |
| 2283 | /** |
| 2284 | * Contains the {@link #calculateExtraLayoutSpace(RecyclerView.State, int[])} extra layout |
| 2285 | * space} that should be excluded for recycling when cleaning up the tail of the list during |
| 2286 | * a smooth scroll. |
| 2287 | */ |
| 2288 | int mNoRecycleSpace = 0; |
| 2289 | |
| 2290 | /** |
| 2291 | * Equal to {@link RecyclerView.State#isPreLayout()}. When consuming scrap, if this value |
| 2292 | * is set to true, we skip removed views since they should not be laid out in post layout |
| 2293 | * step. |
| 2294 | */ |
| 2295 | boolean mIsPreLayout = false; |
| 2296 | |
| 2297 | /** |
| 2298 | * The most recent {@link #scrollBy(int, RecyclerView.Recycler, RecyclerView.State)} |
| 2299 | * amount. |
| 2300 | */ |
| 2301 | int mLastScrollDelta; |
| 2302 | |
| 2303 | /** |
| 2304 | * When LLM needs to layout particular views, it sets this list in which case, LayoutState |
| 2305 | * will only return views from this list and return null if it cannot find an item. |
| 2306 | */ |
| 2307 | List<RecyclerView.ViewHolder> mScrapList = null; |
| 2308 | |
| 2309 | /** |
| 2310 | * Used when there is no limit in how many views can be laid out. |
| 2311 | */ |
| 2312 | boolean mInfinite; |
| 2313 | |
| 2314 | /** |
| 2315 | * @return true if there are more items in the data adapter |
| 2316 | */ |
| 2317 | boolean hasMore(RecyclerView.State state) { |
| 2318 | return mCurrentPosition >= 0 && mCurrentPosition < state.getItemCount(); |
| 2319 | } |
| 2320 | |
| 2321 | /** |
| 2322 | * Gets the view for the next element that we should layout. |
| 2323 | * Also updates current item index to the next item, based on {@link #mItemDirection} |
| 2324 | * |
| 2325 | * @return The next element that we should layout. |
| 2326 | */ |
| 2327 | View next(RecyclerView.Recycler recycler) { |
| 2328 | if (mScrapList != null) { |
| 2329 | return nextViewFromScrapList(); |
| 2330 | } |
| 2331 | final View view = recycler.getViewForPosition(mCurrentPosition); |
| 2332 | mCurrentPosition += mItemDirection; |
| 2333 | return view; |
| 2334 | } |
| 2335 | |
| 2336 | /** |
| 2337 | * Returns the next item from the scrap list. |
| 2338 | * <p> |
| 2339 | * Upon finding a valid VH, sets current item position to VH.itemPosition + mItemDirection |
| 2340 | * |
| 2341 | * @return View if an item in the current position or direction exists if not null. |
| 2342 | */ |
| 2343 | private View nextViewFromScrapList() { |
| 2344 | final int size = mScrapList.size(); |
| 2345 | for (int i = 0; i < size; i++) { |
| 2346 | final View view = mScrapList.get(i).itemView; |
| 2347 | final RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) view.getLayoutParams(); |
| 2348 | if (lp.isItemRemoved()) { |
| 2349 | continue; |
| 2350 | } |
| 2351 | if (mCurrentPosition == lp.getViewLayoutPosition()) { |
| 2352 | assignPositionFromScrapList(view); |
| 2353 | return view; |
| 2354 | } |
| 2355 | } |
| 2356 | return null; |
| 2357 | } |
| 2358 | |
| 2359 | public void assignPositionFromScrapList() { |
| 2360 | assignPositionFromScrapList(null); |
| 2361 | } |
| 2362 | |
| 2363 | public void assignPositionFromScrapList(View ignore) { |
| 2364 | final View closest = nextViewInLimitedList(ignore); |
| 2365 | if (closest == null) { |
| 2366 | mCurrentPosition = RecyclerView.NO_POSITION; |
| 2367 | } else { |
| 2368 | mCurrentPosition = ((RecyclerView.LayoutParams) closest.getLayoutParams()) |
| 2369 | .getViewLayoutPosition(); |
| 2370 | } |
| 2371 | } |
| 2372 | |
| 2373 | public View nextViewInLimitedList(View ignore) { |
| 2374 | int size = mScrapList.size(); |
| 2375 | View closest = null; |
| 2376 | int closestDistance = Integer.MAX_VALUE; |
| 2377 | if (DEBUG && mIsPreLayout) { |
| 2378 | throw new IllegalStateException("Scrap list cannot be used in pre layout"); |
| 2379 | } |
| 2380 | for (int i = 0; i < size; i++) { |
| 2381 | View view = mScrapList.get(i).itemView; |
| 2382 | final RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) view.getLayoutParams(); |
| 2383 | if (view == ignore || lp.isItemRemoved()) { |
| 2384 | continue; |
| 2385 | } |
| 2386 | final int distance = (lp.getViewLayoutPosition() - mCurrentPosition) |
| 2387 | * mItemDirection; |
| 2388 | if (distance < 0) { |
| 2389 | continue; // item is not in current direction |
| 2390 | } |
| 2391 | if (distance < closestDistance) { |
| 2392 | closest = view; |
| 2393 | closestDistance = distance; |
| 2394 | if (distance == 0) { |
| 2395 | break; |
| 2396 | } |
| 2397 | } |
| 2398 | } |
| 2399 | return closest; |
| 2400 | } |
| 2401 | |
| 2402 | void log() { |
| 2403 | Log.d(TAG, "avail:" + mAvailable + ", ind:" + mCurrentPosition + ", dir:" |
| 2404 | + mItemDirection + ", offset:" + mOffset + ", layoutDir:" + mLayoutDirection); |
| 2405 | } |
| 2406 | } |
| 2407 | |
| 2408 | /** |
| 2409 | * @hide |
| 2410 | */ |
| 2411 | @RestrictTo(LIBRARY_GROUP_PREFIX) |
| 2412 | @SuppressLint("BanParcelableUsage") |
| 2413 | public static class SavedState implements Parcelable { |
| 2414 | |
| 2415 | int mAnchorPosition; |
| 2416 | |
| 2417 | int mAnchorOffset; |
| 2418 | |
| 2419 | boolean mAnchorLayoutFromEnd; |
| 2420 | |
| 2421 | public SavedState() { |
| 2422 | |
| 2423 | } |
| 2424 | |
| 2425 | SavedState(Parcel in) { |
| 2426 | mAnchorPosition = in.readInt(); |
| 2427 | mAnchorOffset = in.readInt(); |
| 2428 | mAnchorLayoutFromEnd = in.readInt() == 1; |
| 2429 | } |
| 2430 | |
| 2431 | public SavedState(SavedState other) { |
| 2432 | mAnchorPosition = other.mAnchorPosition; |
| 2433 | mAnchorOffset = other.mAnchorOffset; |
| 2434 | mAnchorLayoutFromEnd = other.mAnchorLayoutFromEnd; |
| 2435 | } |
| 2436 | |
| 2437 | boolean hasValidAnchor() { |
| 2438 | return mAnchorPosition >= 0; |
| 2439 | } |
| 2440 | |
| 2441 | void invalidateAnchor() { |
| 2442 | mAnchorPosition = RecyclerView.NO_POSITION; |
| 2443 | } |
| 2444 | |
| 2445 | @Override |
| 2446 | public int describeContents() { |
| 2447 | return 0; |
| 2448 | } |
| 2449 | |
| 2450 | @Override |
| 2451 | public void writeToParcel(Parcel dest, int flags) { |
| 2452 | dest.writeInt(mAnchorPosition); |
| 2453 | dest.writeInt(mAnchorOffset); |
| 2454 | dest.writeInt(mAnchorLayoutFromEnd ? 1 : 0); |
| 2455 | } |
| 2456 | |
| 2457 | public static final Parcelable.Creator<SavedState> CREATOR = |
| 2458 | new Parcelable.Creator<SavedState>() { |
| 2459 | @Override |
| 2460 | public SavedState createFromParcel(Parcel in) { |
| 2461 | return new SavedState(in); |
| 2462 | } |
| 2463 | |
| 2464 | @Override |
| 2465 | public SavedState[] newArray(int size) { |
| 2466 | return new SavedState[size]; |
| 2467 | } |
| 2468 | }; |
| 2469 | } |
| 2470 | |
| 2471 | /** |
| 2472 | * Simple data class to keep Anchor information |
| 2473 | */ |
| 2474 | static class AnchorInfo { |
| 2475 | OrientationHelper mOrientationHelper; |
| 2476 | int mPosition; |
| 2477 | int mCoordinate; |
| 2478 | boolean mLayoutFromEnd; |
| 2479 | boolean mValid; |
| 2480 | |
| 2481 | AnchorInfo() { |
| 2482 | reset(); |
| 2483 | } |
| 2484 | |
| 2485 | void reset() { |
| 2486 | mPosition = RecyclerView.NO_POSITION; |
| 2487 | mCoordinate = INVALID_OFFSET; |
| 2488 | mLayoutFromEnd = false; |
| 2489 | mValid = false; |
| 2490 | } |
| 2491 | |
| 2492 | /** |
| 2493 | * assigns anchor coordinate from the RecyclerView's padding depending on current |
| 2494 | * layoutFromEnd value |
| 2495 | */ |
| 2496 | void assignCoordinateFromPadding() { |
| 2497 | mCoordinate = mLayoutFromEnd |
| 2498 | ? mOrientationHelper.getEndAfterPadding() |
| 2499 | : mOrientationHelper.getStartAfterPadding(); |
| 2500 | } |
| 2501 | |
| 2502 | @Override |
| 2503 | public String toString() { |
| 2504 | return "AnchorInfo{" |
| 2505 | + "mPosition=" + mPosition |
| 2506 | + ", mCoordinate=" + mCoordinate |
| 2507 | + ", mLayoutFromEnd=" + mLayoutFromEnd |
| 2508 | + ", mValid=" + mValid |
| 2509 | + '}'; |
| 2510 | } |
| 2511 | |
| 2512 | boolean isViewValidAsAnchor(View child, RecyclerView.State state) { |
| 2513 | RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) child.getLayoutParams(); |
| 2514 | return !lp.isItemRemoved() && lp.getViewLayoutPosition() >= 0 |
| 2515 | && lp.getViewLayoutPosition() < state.getItemCount(); |
| 2516 | } |
| 2517 | |
| 2518 | public void assignFromViewAndKeepVisibleRect(View child, int position) { |
| 2519 | final int spaceChange = mOrientationHelper.getTotalSpaceChange(); |
| 2520 | if (spaceChange >= 0) { |
| 2521 | assignFromView(child, position); |
| 2522 | return; |
| 2523 | } |
| 2524 | mPosition = position; |
| 2525 | if (mLayoutFromEnd) { |
| 2526 | final int prevLayoutEnd = mOrientationHelper.getEndAfterPadding() - spaceChange; |
| 2527 | final int childEnd = mOrientationHelper.getDecoratedEnd(child); |
| 2528 | final int previousEndMargin = prevLayoutEnd - childEnd; |
| 2529 | mCoordinate = mOrientationHelper.getEndAfterPadding() - previousEndMargin; |
| 2530 | // ensure we did not push child's top out of bounds because of this |
| 2531 | if (previousEndMargin > 0) { // we have room to shift bottom if necessary |
| 2532 | final int childSize = mOrientationHelper.getDecoratedMeasurement(child); |
| 2533 | final int estimatedChildStart = mCoordinate - childSize; |
| 2534 | final int layoutStart = mOrientationHelper.getStartAfterPadding(); |
| 2535 | final int previousStartMargin = mOrientationHelper.getDecoratedStart(child) |
| 2536 | - layoutStart; |
| 2537 | final int startReference = layoutStart + Math.min(previousStartMargin, 0); |
| 2538 | final int startMargin = estimatedChildStart - startReference; |
| 2539 | if (startMargin < 0) { |
| 2540 | // offset to make top visible but not too much |
| 2541 | mCoordinate += Math.min(previousEndMargin, -startMargin); |
| 2542 | } |
| 2543 | } |
| 2544 | } else { |
| 2545 | final int childStart = mOrientationHelper.getDecoratedStart(child); |
| 2546 | final int startMargin = childStart - mOrientationHelper.getStartAfterPadding(); |
| 2547 | mCoordinate = childStart; |
| 2548 | if (startMargin > 0) { // we have room to fix end as well |
| 2549 | final int estimatedEnd = childStart |
| 2550 | + mOrientationHelper.getDecoratedMeasurement(child); |
| 2551 | final int previousLayoutEnd = mOrientationHelper.getEndAfterPadding() |
| 2552 | - spaceChange; |
| 2553 | final int previousEndMargin = previousLayoutEnd |
| 2554 | - mOrientationHelper.getDecoratedEnd(child); |
| 2555 | final int endReference = mOrientationHelper.getEndAfterPadding() |
| 2556 | - Math.min(0, previousEndMargin); |
| 2557 | final int endMargin = endReference - estimatedEnd; |
| 2558 | if (endMargin < 0) { |
| 2559 | mCoordinate -= Math.min(startMargin, -endMargin); |
| 2560 | } |
| 2561 | } |
| 2562 | } |
| 2563 | } |
| 2564 | |
| 2565 | public void assignFromView(View child, int position) { |
| 2566 | if (mLayoutFromEnd) { |
| 2567 | mCoordinate = mOrientationHelper.getDecoratedEnd(child) |
| 2568 | + mOrientationHelper.getTotalSpaceChange(); |
| 2569 | } else { |
| 2570 | mCoordinate = mOrientationHelper.getDecoratedStart(child); |
| 2571 | } |
| 2572 | |
| 2573 | mPosition = position; |
| 2574 | } |
| 2575 | } |
| 2576 | |
| 2577 | protected static class LayoutChunkResult { |
| 2578 | public int mConsumed; |
| 2579 | public boolean mFinished; |
| 2580 | public boolean mIgnoreConsumed; |
| 2581 | public boolean mFocusable; |
| 2582 | |
| 2583 | void resetInternal() { |
| 2584 | mConsumed = 0; |
| 2585 | mFinished = false; |
| 2586 | mIgnoreConsumed = false; |
| 2587 | mFocusable = false; |
| 2588 | } |
| 2589 | } |
| 2590 | |
| 2591 | public void setNeedFixGap(boolean needFixGap) { |
| 2592 | this.needFixGap = needFixGap; |
| 2593 | } |
| 2594 | } |
| 2595 | |