| 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 | package androidx.recyclerview.widget; |
| 17 | |
| 18 | import android.content.Context; |
| 19 | import android.graphics.Rect; |
| 20 | import android.util.AttributeSet; |
| 21 | import android.util.Log; |
| 22 | import android.util.SparseIntArray; |
| 23 | import android.view.View; |
| 24 | import android.view.ViewGroup; |
| 25 | |
| 26 | import androidx.core.view.accessibility.AccessibilityNodeInfoCompat; |
| 27 | |
| 28 | import org.telegram.messenger.AndroidUtilities; |
| 29 | import org.telegram.messenger.BuildVars; |
| 30 | |
| 31 | import java.util.Arrays; |
| 32 | |
| 33 | /** |
| 34 | * A {@link RecyclerView.LayoutManager} implementations that lays out items in a grid. |
| 35 | * <p> |
| 36 | * By default, each item occupies 1 span. You can change it by providing a custom |
| 37 | * {@link SpanSizeLookup} instance via {@link #setSpanSizeLookup(SpanSizeLookup)}. |
| 38 | */ |
| 39 | public class GridLayoutManager extends LinearLayoutManager { |
| 40 | |
| 41 | private static final boolean DEBUG = BuildVars.DEBUG_VERSION; |
| 42 | private static final String TAG = "GridLayoutManager"; |
| 43 | public static final int DEFAULT_SPAN_COUNT = -1; |
| 44 | /** |
| 45 | * Span size have been changed but we've not done a new layout calculation. |
| 46 | */ |
| 47 | boolean mPendingSpanCountChange = false; |
| 48 | int mSpanCount = DEFAULT_SPAN_COUNT; |
| 49 | /** |
| 50 | * Right borders for each span. |
| 51 | * <p>For <b>i-th</b> item start is {@link #mCachedBorders}[i-1] + 1 |
| 52 | * and end is {@link #mCachedBorders}[i]. |
| 53 | */ |
| 54 | protected int [] mCachedBorders; |
| 55 | /** |
| 56 | * Temporary array to keep views in layoutChunk method |
| 57 | */ |
| 58 | View[] mSet; |
| 59 | final SparseIntArray mPreLayoutSpanSizeCache = new SparseIntArray(); |
| 60 | final SparseIntArray mPreLayoutSpanIndexCache = new SparseIntArray(); |
| 61 | SpanSizeLookup mSpanSizeLookup = new DefaultSpanSizeLookup(); |
| 62 | // re-used variable to acquire decor insets from RecyclerView |
| 63 | final Rect mDecorInsets = new Rect(); |
| 64 | |
| 65 | private boolean mUsingSpansToEstimateScrollBarDimensions; |
| 66 | |
| 67 | /** |
| 68 | * Creates a vertical GridLayoutManager |
| 69 | * |
| 70 | * @param context Current context, will be used to access resources. |
| 71 | * @param spanCount The number of columns in the grid |
| 72 | */ |
| 73 | public GridLayoutManager(Context context, int spanCount) { |
| 74 | super(context); |
| 75 | setSpanCount(spanCount); |
| 76 | } |
| 77 | |
| 78 | /** |
| 79 | * @param context Current context, will be used to access resources. |
| 80 | * @param spanCount The number of columns or rows in the grid |
| 81 | * @param orientation Layout orientation. Should be {@link #HORIZONTAL} or {@link |
| 82 | * #VERTICAL}. |
| 83 | * @param reverseLayout When set to true, layouts from end to start. |
| 84 | */ |
| 85 | public GridLayoutManager(Context context, int spanCount, |
| 86 | @RecyclerView.Orientation int orientation, boolean reverseLayout) { |
| 87 | super(context, orientation, reverseLayout); |
| 88 | setSpanCount(spanCount); |
| 89 | } |
| 90 | |
| 91 | /** |
| 92 | * stackFromEnd is not supported by GridLayoutManager. Consider using |
| 93 | * {@link #setReverseLayout(boolean)}. |
| 94 | */ |
| 95 | @Override |
| 96 | public void setStackFromEnd(boolean stackFromEnd) { |
| 97 | if (stackFromEnd) { |
| 98 | throw new UnsupportedOperationException( |
| 99 | "GridLayoutManager does not support stack from end." |
| 100 | + " Consider using reverse layout"); |
| 101 | } |
| 102 | super.setStackFromEnd(false); |
| 103 | } |
| 104 | |
| 105 | @Override |
| 106 | public int getRowCountForAccessibility(RecyclerView.Recycler recycler, |
| 107 | RecyclerView.State state) { |
| 108 | if (mOrientation == HORIZONTAL) { |
| 109 | return mSpanCount; |
| 110 | } |
| 111 | if (state.getItemCount() < 1) { |
| 112 | return 0; |
| 113 | } |
| 114 | |
| 115 | // Row count is one more than the last item's row index. |
| 116 | return getSpanGroupIndex(recycler, state, state.getItemCount() - 1) + 1; |
| 117 | } |
| 118 | |
| 119 | @Override |
| 120 | public int getColumnCountForAccessibility(RecyclerView.Recycler recycler, |
| 121 | RecyclerView.State state) { |
| 122 | if (mOrientation == VERTICAL) { |
| 123 | return mSpanCount; |
| 124 | } |
| 125 | if (state.getItemCount() < 1) { |
| 126 | return 0; |
| 127 | } |
| 128 | |
| 129 | // Column count is one more than the last item's column index. |
| 130 | return getSpanGroupIndex(recycler, state, state.getItemCount() - 1) + 1; |
| 131 | } |
| 132 | |
| 133 | @Override |
| 134 | public void onInitializeAccessibilityNodeInfoForItem(RecyclerView.Recycler recycler, |
| 135 | RecyclerView.State state, View host, AccessibilityNodeInfoCompat info) { |
| 136 | ViewGroup.LayoutParams lp = host.getLayoutParams(); |
| 137 | if (!(lp instanceof LayoutParams)) { |
| 138 | super.onInitializeAccessibilityNodeInfoForItem(host, info); |
| 139 | return; |
| 140 | } |
| 141 | LayoutParams glp = (LayoutParams) lp; |
| 142 | int spanGroupIndex = getSpanGroupIndex(recycler, state, glp.getViewLayoutPosition()); |
| 143 | if (mOrientation == HORIZONTAL) { |
| 144 | info.setCollectionItemInfo(AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain( |
| 145 | glp.getSpanIndex(), glp.getSpanSize(), |
| 146 | spanGroupIndex, 1, |
| 147 | mSpanCount > 1 && glp.getSpanSize() == mSpanCount, false)); |
| 148 | } else { // VERTICAL |
| 149 | info.setCollectionItemInfo(AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain( |
| 150 | spanGroupIndex , 1, |
| 151 | glp.getSpanIndex(), glp.getSpanSize(), |
| 152 | mSpanCount > 1 && glp.getSpanSize() == mSpanCount, false)); |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | @Override |
| 157 | public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { |
| 158 | if (state.isPreLayout()) { |
| 159 | cachePreLayoutSpanMapping(); |
| 160 | } |
| 161 | super.onLayoutChildren(recycler, state); |
| 162 | if (DEBUG) { |
| 163 | validateChildOrder(); |
| 164 | } |
| 165 | clearPreLayoutSpanMappingCache(); |
| 166 | } |
| 167 | |
| 168 | @Override |
| 169 | public void onLayoutCompleted(RecyclerView.State state) { |
| 170 | super.onLayoutCompleted(state); |
| 171 | mPendingSpanCountChange = false; |
| 172 | } |
| 173 | |
| 174 | private void clearPreLayoutSpanMappingCache() { |
| 175 | mPreLayoutSpanSizeCache.clear(); |
| 176 | mPreLayoutSpanIndexCache.clear(); |
| 177 | } |
| 178 | |
| 179 | private void cachePreLayoutSpanMapping() { |
| 180 | final int childCount = getChildCount(); |
| 181 | for (int i = 0; i < childCount; i++) { |
| 182 | final LayoutParams lp = (LayoutParams) getChildAt(i).getLayoutParams(); |
| 183 | final int viewPosition = lp.getViewLayoutPosition(); |
| 184 | mPreLayoutSpanSizeCache.put(viewPosition, lp.getSpanSize()); |
| 185 | mPreLayoutSpanIndexCache.put(viewPosition, lp.getSpanIndex()); |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | @Override |
| 190 | public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) { |
| 191 | mSpanSizeLookup.invalidateSpanIndexCache(); |
| 192 | mSpanSizeLookup.invalidateSpanGroupIndexCache(); |
| 193 | } |
| 194 | |
| 195 | @Override |
| 196 | public void onItemsChanged(RecyclerView recyclerView) { |
| 197 | mSpanSizeLookup.invalidateSpanIndexCache(); |
| 198 | mSpanSizeLookup.invalidateSpanGroupIndexCache(); |
| 199 | } |
| 200 | |
| 201 | @Override |
| 202 | public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) { |
| 203 | mSpanSizeLookup.invalidateSpanIndexCache(); |
| 204 | mSpanSizeLookup.invalidateSpanGroupIndexCache(); |
| 205 | } |
| 206 | |
| 207 | @Override |
| 208 | public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount, |
| 209 | Object payload) { |
| 210 | mSpanSizeLookup.invalidateSpanIndexCache(); |
| 211 | mSpanSizeLookup.invalidateSpanGroupIndexCache(); |
| 212 | } |
| 213 | |
| 214 | @Override |
| 215 | public void onItemsMoved(RecyclerView recyclerView, int from, int to, int itemCount) { |
| 216 | mSpanSizeLookup.invalidateSpanIndexCache(); |
| 217 | mSpanSizeLookup.invalidateSpanGroupIndexCache(); |
| 218 | } |
| 219 | |
| 220 | @Override |
| 221 | public RecyclerView.LayoutParams generateDefaultLayoutParams() { |
| 222 | if (mOrientation == HORIZONTAL) { |
| 223 | return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, |
| 224 | ViewGroup.LayoutParams.MATCH_PARENT); |
| 225 | } else { |
| 226 | return new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, |
| 227 | ViewGroup.LayoutParams.WRAP_CONTENT); |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | @Override |
| 232 | public RecyclerView.LayoutParams generateLayoutParams(Context c, AttributeSet attrs) { |
| 233 | return new LayoutParams(c, attrs); |
| 234 | } |
| 235 | |
| 236 | @Override |
| 237 | public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { |
| 238 | if (lp instanceof ViewGroup.MarginLayoutParams) { |
| 239 | return new LayoutParams((ViewGroup.MarginLayoutParams) lp); |
| 240 | } else { |
| 241 | return new LayoutParams(lp); |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | @Override |
| 246 | public boolean checkLayoutParams(RecyclerView.LayoutParams lp) { |
| 247 | return lp instanceof LayoutParams; |
| 248 | } |
| 249 | |
| 250 | /** |
| 251 | * Sets the source to get the number of spans occupied by each item in the adapter. |
| 252 | * |
| 253 | * @param spanSizeLookup {@link SpanSizeLookup} instance to be used to query number of spans |
| 254 | * occupied by each item |
| 255 | */ |
| 256 | public void setSpanSizeLookup(SpanSizeLookup spanSizeLookup) { |
| 257 | mSpanSizeLookup = spanSizeLookup; |
| 258 | } |
| 259 | |
| 260 | /** |
| 261 | * Returns the current {@link SpanSizeLookup} used by the GridLayoutManager. |
| 262 | * |
| 263 | * @return The current {@link SpanSizeLookup} used by the GridLayoutManager. |
| 264 | */ |
| 265 | public SpanSizeLookup getSpanSizeLookup() { |
| 266 | return mSpanSizeLookup; |
| 267 | } |
| 268 | |
| 269 | private void updateMeasurements() { |
| 270 | int totalSpace; |
| 271 | if (getOrientation() == VERTICAL) { |
| 272 | totalSpace = getWidth() - getPaddingRight() - getPaddingLeft(); |
| 273 | } else { |
| 274 | totalSpace = getHeight() - getPaddingBottom() - getPaddingTop(); |
| 275 | } |
| 276 | calculateItemBorders(totalSpace); |
| 277 | } |
| 278 | |
| 279 | @Override |
| 280 | public void setMeasuredDimension(Rect childrenBounds, int wSpec, int hSpec) { |
| 281 | if (mCachedBorders == null) { |
| 282 | super.setMeasuredDimension(childrenBounds, wSpec, hSpec); |
| 283 | } |
| 284 | final int width, height; |
| 285 | final int horizontalPadding = getPaddingLeft() + getPaddingRight(); |
| 286 | final int verticalPadding = getPaddingTop() + getPaddingBottom(); |
| 287 | if (mOrientation == VERTICAL) { |
| 288 | final int usedHeight = childrenBounds.height() + verticalPadding; |
| 289 | height = chooseSize(hSpec, usedHeight, getMinimumHeight()); |
| 290 | width = chooseSize(wSpec, mCachedBorders[mCachedBorders.length - 1] + horizontalPadding, |
| 291 | getMinimumWidth()); |
| 292 | } else { |
| 293 | final int usedWidth = childrenBounds.width() + horizontalPadding; |
| 294 | width = chooseSize(wSpec, usedWidth, getMinimumWidth()); |
| 295 | height = chooseSize(hSpec, mCachedBorders[mCachedBorders.length - 1] + verticalPadding, |
| 296 | getMinimumHeight()); |
| 297 | } |
| 298 | setMeasuredDimension(width, height); |
| 299 | } |
| 300 | |
| 301 | /** |
| 302 | * @param totalSpace Total available space after padding is removed |
| 303 | */ |
| 304 | private void calculateItemBorders(int totalSpace) { |
| 305 | mCachedBorders = calculateItemBorders(mCachedBorders, mSpanCount, totalSpace); |
| 306 | } |
| 307 | |
| 308 | /** |
| 309 | * @param cachedBorders The out array |
| 310 | * @param spanCount number of spans |
| 311 | * @param totalSpace total available space after padding is removed |
| 312 | * @return The updated array. Might be the same instance as the provided array if its size |
| 313 | * has not changed. |
| 314 | */ |
| 315 | protected int[] calculateItemBorders(int[] cachedBorders, int spanCount, int totalSpace) { |
| 316 | if (cachedBorders == null || cachedBorders.length != spanCount + 1 |
| 317 | || cachedBorders[cachedBorders.length - 1] != totalSpace) { |
| 318 | cachedBorders = new int[spanCount + 1]; |
| 319 | } |
| 320 | cachedBorders[0] = 0; |
| 321 | int sizePerSpan = totalSpace / spanCount; |
| 322 | int sizePerSpanRemainder = totalSpace % spanCount; |
| 323 | int consumedPixels = 0; |
| 324 | int additionalSize = 0; |
| 325 | for (int i = 1; i <= spanCount; i++) { |
| 326 | int itemSize = sizePerSpan; |
| 327 | additionalSize += sizePerSpanRemainder; |
| 328 | if (additionalSize > 0 && (spanCount - additionalSize) < sizePerSpanRemainder) { |
| 329 | itemSize += 1; |
| 330 | additionalSize -= spanCount; |
| 331 | } |
| 332 | consumedPixels += itemSize; |
| 333 | cachedBorders[i] = consumedPixels; |
| 334 | } |
| 335 | return cachedBorders; |
| 336 | } |
| 337 | |
| 338 | int getSpaceForSpanRange(int startSpan, int spanSize) { |
| 339 | if (mOrientation == VERTICAL && isLayoutRTL()) { |
| 340 | return mCachedBorders[mSpanCount - startSpan] |
| 341 | - mCachedBorders[mSpanCount - startSpan - spanSize]; |
| 342 | } else { |
| 343 | return mCachedBorders[startSpan + spanSize] - mCachedBorders[startSpan]; |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | @Override |
| 348 | void onAnchorReady(RecyclerView.Recycler recycler, RecyclerView.State state, |
| 349 | AnchorInfo anchorInfo, int itemDirection) { |
| 350 | super.onAnchorReady(recycler, state, anchorInfo, itemDirection); |
| 351 | updateMeasurements(); |
| 352 | if (state.getItemCount() > 0 && !state.isPreLayout()) { |
| 353 | ensureAnchorIsInCorrectSpan(recycler, state, anchorInfo, itemDirection); |
| 354 | } |
| 355 | ensureViewSet(); |
| 356 | } |
| 357 | |
| 358 | private void ensureViewSet() { |
| 359 | if (mSet == null || mSet.length != mSpanCount) { |
| 360 | mSet = new View[mSpanCount]; |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | @Override |
| 365 | public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, |
| 366 | RecyclerView.State state) { |
| 367 | updateMeasurements(); |
| 368 | ensureViewSet(); |
| 369 | return super.scrollHorizontallyBy(dx, recycler, state); |
| 370 | } |
| 371 | |
| 372 | @Override |
| 373 | public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, |
| 374 | RecyclerView.State state) { |
| 375 | updateMeasurements(); |
| 376 | ensureViewSet(); |
| 377 | return super.scrollVerticallyBy(dy, recycler, state); |
| 378 | } |
| 379 | |
| 380 | private void ensureAnchorIsInCorrectSpan(RecyclerView.Recycler recycler, |
| 381 | RecyclerView.State state, AnchorInfo anchorInfo, int itemDirection) { |
| 382 | final boolean layingOutInPrimaryDirection = |
| 383 | itemDirection == LayoutState.ITEM_DIRECTION_TAIL; |
| 384 | int span = getSpanIndex(recycler, state, anchorInfo.mPosition); |
| 385 | if (layingOutInPrimaryDirection) { |
| 386 | // choose span 0 |
| 387 | while (span > 0 && anchorInfo.mPosition > 0) { |
| 388 | anchorInfo.mPosition--; |
| 389 | span = getSpanIndex(recycler, state, anchorInfo.mPosition); |
| 390 | } |
| 391 | } else { |
| 392 | // choose the max span we can get. hopefully last one |
| 393 | final int indexLimit = state.getItemCount() - 1; |
| 394 | int pos = anchorInfo.mPosition; |
| 395 | int bestSpan = span; |
| 396 | while (pos < indexLimit) { |
| 397 | int next = getSpanIndex(recycler, state, pos + 1); |
| 398 | if (next > bestSpan) { |
| 399 | pos += 1; |
| 400 | bestSpan = next; |
| 401 | } else { |
| 402 | break; |
| 403 | } |
| 404 | } |
| 405 | anchorInfo.mPosition = pos; |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | @Override |
| 410 | View findReferenceChild(RecyclerView.Recycler recycler, RecyclerView.State state, |
| 411 | int start, int end, int itemCount) { |
| 412 | ensureLayoutState(); |
| 413 | View invalidMatch = null; |
| 414 | View outOfBoundsMatch = null; |
| 415 | final int boundsStart = mOrientationHelper.getStartAfterPadding(); |
| 416 | final int boundsEnd = mOrientationHelper.getEndAfterPadding(); |
| 417 | final int diff = end > start ? 1 : -1; |
| 418 | |
| 419 | for (int i = start; i != end; i += diff) { |
| 420 | final View view = getChildAt(i); |
| 421 | final int position = getPosition(view); |
| 422 | if (position >= 0 && position < itemCount) { |
| 423 | final int span = getSpanIndex(recycler, state, position); |
| 424 | if (span != 0) { |
| 425 | continue; |
| 426 | } |
| 427 | if (((RecyclerView.LayoutParams) view.getLayoutParams()).isItemRemoved()) { |
| 428 | if (invalidMatch == null) { |
| 429 | invalidMatch = view; // removed item, least preferred |
| 430 | } |
| 431 | } else if (mOrientationHelper.getDecoratedStart(view) >= boundsEnd |
| 432 | || mOrientationHelper.getDecoratedEnd(view) < boundsStart) { |
| 433 | if (outOfBoundsMatch == null) { |
| 434 | outOfBoundsMatch = view; // item is not visible, less preferred |
| 435 | } |
| 436 | } else { |
| 437 | return view; |
| 438 | } |
| 439 | } |
| 440 | } |
| 441 | return outOfBoundsMatch != null ? outOfBoundsMatch : invalidMatch; |
| 442 | } |
| 443 | |
| 444 | private int getSpanGroupIndex(RecyclerView.Recycler recycler, RecyclerView.State state, |
| 445 | int viewPosition) { |
| 446 | if (!state.isPreLayout()) { |
| 447 | return mSpanSizeLookup.getCachedSpanGroupIndex(viewPosition, mSpanCount); |
| 448 | } |
| 449 | final int adapterPosition = recycler.convertPreLayoutPositionToPostLayout(viewPosition); |
| 450 | if (adapterPosition == -1) { |
| 451 | if (DEBUG) { |
| 452 | throw new RuntimeException("Cannot find span group index for position " |
| 453 | + viewPosition); |
| 454 | } |
| 455 | Log.w(TAG, "Cannot find span size for pre layout position. " + viewPosition); |
| 456 | return 0; |
| 457 | } |
| 458 | return mSpanSizeLookup.getCachedSpanGroupIndex(adapterPosition, mSpanCount); |
| 459 | } |
| 460 | |
| 461 | private int getSpanIndex(RecyclerView.Recycler recycler, RecyclerView.State state, int pos) { |
| 462 | if (!state.isPreLayout()) { |
| 463 | return mSpanSizeLookup.getCachedSpanIndex(pos, mSpanCount); |
| 464 | } |
| 465 | final int cached = mPreLayoutSpanIndexCache.get(pos, -1); |
| 466 | if (cached != -1) { |
| 467 | return cached; |
| 468 | } |
| 469 | final int adapterPosition = recycler.convertPreLayoutPositionToPostLayout(pos); |
| 470 | if (adapterPosition == -1) { |
| 471 | if (DEBUG) { |
| 472 | throw new RuntimeException("Cannot find span index for pre layout position. It is" |
| 473 | + " not cached, not in the adapter. Pos:" + pos); |
| 474 | } |
| 475 | Log.w(TAG, "Cannot find span size for pre layout position. It is" |
| 476 | + " not cached, not in the adapter. Pos:" + pos); |
| 477 | return 0; |
| 478 | } |
| 479 | return mSpanSizeLookup.getCachedSpanIndex(adapterPosition, mSpanCount); |
| 480 | } |
| 481 | |
| 482 | protected int getSpanSize(RecyclerView.Recycler recycler, RecyclerView.State state, int pos) { |
| 483 | if (!state.isPreLayout()) { |
| 484 | return mSpanSizeLookup.getSpanSize(pos); |
| 485 | } |
| 486 | final int cached = mPreLayoutSpanSizeCache.get(pos, -1); |
| 487 | if (cached != -1) { |
| 488 | return cached; |
| 489 | } |
| 490 | final int adapterPosition = recycler.convertPreLayoutPositionToPostLayout(pos); |
| 491 | if (adapterPosition == -1) { |
| 492 | if (DEBUG) { |
| 493 | throw new RuntimeException("Cannot find span size for pre layout position. It is" |
| 494 | + " not cached, not in the adapter. Pos:" + pos); |
| 495 | } |
| 496 | Log.w(TAG, "Cannot find span size for pre layout position. It is" |
| 497 | + " not cached, not in the adapter. Pos:" + pos); |
| 498 | return 1; |
| 499 | } |
| 500 | return mSpanSizeLookup.getSpanSize(adapterPosition); |
| 501 | } |
| 502 | |
| 503 | @Override |
| 504 | void collectPrefetchPositionsForLayoutState(RecyclerView.State state, LayoutState layoutState, |
| 505 | LayoutPrefetchRegistry layoutPrefetchRegistry) { |
| 506 | int remainingSpan = mSpanCount; |
| 507 | int count = 0; |
| 508 | while (count < mSpanCount && layoutState.hasMore(state) && remainingSpan > 0) { |
| 509 | final int pos = layoutState.mCurrentPosition; |
| 510 | layoutPrefetchRegistry.addPosition(pos, Math.max(0, layoutState.mScrollingOffset)); |
| 511 | final int spanSize = mSpanSizeLookup.getSpanSize(pos); |
| 512 | remainingSpan -= spanSize; |
| 513 | layoutState.mCurrentPosition += layoutState.mItemDirection; |
| 514 | count++; |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | @Override |
| 519 | void layoutChunk(RecyclerView.Recycler recycler, RecyclerView.State state, |
| 520 | LayoutState layoutState, LayoutChunkResult result) { |
| 521 | final int otherDirSpecMode = mOrientationHelper.getModeInOther(); |
| 522 | final boolean flexibleInOtherDir = otherDirSpecMode != View.MeasureSpec.EXACTLY; |
| 523 | final int currentOtherDirSize = getChildCount() > 0 ? mCachedBorders[mSpanCount] : 0; |
| 524 | // if grid layout's dimensions are not specified, let the new row change the measurements |
| 525 | // This is not perfect since we not covering all rows but still solves an important case |
| 526 | // where they may have a header row which should be laid out according to children. |
| 527 | if (flexibleInOtherDir) { |
| 528 | updateMeasurements(); // reset measurements |
| 529 | } |
| 530 | final boolean layingOutInPrimaryDirection = |
| 531 | layoutState.mItemDirection == LayoutState.ITEM_DIRECTION_TAIL; |
| 532 | int count = 0; |
| 533 | int consumedSpanCount = 0; |
| 534 | int remainingSpan = mSpanCount; |
| 535 | if (!layingOutInPrimaryDirection) { |
| 536 | int itemSpanIndex = getSpanIndex(recycler, state, layoutState.mCurrentPosition); |
| 537 | int itemSpanSize = getSpanSize(recycler, state, layoutState.mCurrentPosition); |
| 538 | remainingSpan = itemSpanIndex + itemSpanSize; |
| 539 | } |
| 540 | while (count < mSpanCount && layoutState.hasMore(state) && remainingSpan > 0) { |
| 541 | int pos = layoutState.mCurrentPosition; |
| 542 | final int spanSize = getSpanSize(recycler, state, pos); |
| 543 | if (spanSize > mSpanCount) { |
| 544 | throw new IllegalArgumentException("Item at position " + pos + " requires " |
| 545 | + spanSize + " spans but GridLayoutManager has only " + mSpanCount |
| 546 | + " spans."); |
| 547 | } |
| 548 | remainingSpan -= spanSize; |
| 549 | if (remainingSpan < 0) { |
| 550 | break; // item did not fit into this row or column |
| 551 | } |
| 552 | View view = layoutState.next(recycler); |
| 553 | if (view == null) { |
| 554 | break; |
| 555 | } |
| 556 | consumedSpanCount += spanSize; |
| 557 | mSet[count] = view; |
| 558 | count++; |
| 559 | } |
| 560 | |
| 561 | if (count == 0) { |
| 562 | result.mFinished = true; |
| 563 | return; |
| 564 | } |
| 565 | |
| 566 | int maxSize = 0; |
| 567 | float maxSizeInOther = 0; // use a float to get size per span |
| 568 | |
| 569 | // we should assign spans before item decor offsets are calculated |
| 570 | assignSpans(recycler, state, count, layingOutInPrimaryDirection); |
| 571 | for (int i = 0; i < count; i++) { |
| 572 | View view = mSet[i]; |
| 573 | if (layoutState.mScrapList == null) { |
| 574 | if (layingOutInPrimaryDirection) { |
| 575 | addView(view); |
| 576 | } else { |
| 577 | addView(view, 0); |
| 578 | } |
| 579 | } else { |
| 580 | if (layingOutInPrimaryDirection) { |
| 581 | addDisappearingView(view); |
| 582 | } else { |
| 583 | addDisappearingView(view, 0); |
| 584 | } |
| 585 | } |
| 586 | calculateItemDecorationsForChild(view, mDecorInsets); |
| 587 | |
| 588 | measureChild(view, otherDirSpecMode, false); |
| 589 | final int size = mOrientationHelper.getDecoratedMeasurement(view); |
| 590 | if (size > maxSize) { |
| 591 | maxSize = size; |
| 592 | } |
| 593 | final LayoutParams lp = (LayoutParams) view.getLayoutParams(); |
| 594 | final float otherSize = 1f * mOrientationHelper.getDecoratedMeasurementInOther(view) |
| 595 | / lp.mSpanSize; |
| 596 | if (otherSize > maxSizeInOther) { |
| 597 | maxSizeInOther = otherSize; |
| 598 | } |
| 599 | } |
| 600 | if (flexibleInOtherDir) { |
| 601 | // re-distribute columns |
| 602 | guessMeasurement(maxSizeInOther, currentOtherDirSize); |
| 603 | // now we should re-measure any item that was match parent. |
| 604 | maxSize = 0; |
| 605 | for (int i = 0; i < count; i++) { |
| 606 | View view = mSet[i]; |
| 607 | measureChild(view, View.MeasureSpec.EXACTLY, true); |
| 608 | final int size = mOrientationHelper.getDecoratedMeasurement(view); |
| 609 | if (size > maxSize) { |
| 610 | maxSize = size; |
| 611 | } |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | // Views that did not measure the maxSize has to be re-measured |
| 616 | // We will stop doing this once we introduce Gravity in the GLM layout params |
| 617 | for (int i = 0; i < count; i++) { |
| 618 | final View view = mSet[i]; |
| 619 | if (mOrientationHelper.getDecoratedMeasurement(view) != maxSize) { |
| 620 | final LayoutParams lp = (LayoutParams) view.getLayoutParams(); |
| 621 | final Rect decorInsets = lp.mDecorInsets; |
| 622 | final int verticalInsets = decorInsets.top + decorInsets.bottom |
| 623 | + lp.topMargin + lp.bottomMargin; |
| 624 | final int horizontalInsets = decorInsets.left + decorInsets.right |
| 625 | + lp.leftMargin + lp.rightMargin; |
| 626 | final int totalSpaceInOther = getSpaceForSpanRange(lp.mSpanIndex, lp.mSpanSize); |
| 627 | final int wSpec; |
| 628 | final int hSpec; |
| 629 | if (mOrientation == VERTICAL) { |
| 630 | wSpec = getChildMeasureSpec(totalSpaceInOther, View.MeasureSpec.EXACTLY, |
| 631 | horizontalInsets, lp.width, false); |
| 632 | hSpec = View.MeasureSpec.makeMeasureSpec(maxSize - verticalInsets, |
| 633 | View.MeasureSpec.EXACTLY); |
| 634 | } else { |
| 635 | wSpec = View.MeasureSpec.makeMeasureSpec(maxSize - horizontalInsets, |
| 636 | View.MeasureSpec.EXACTLY); |
| 637 | hSpec = getChildMeasureSpec(totalSpaceInOther, View.MeasureSpec.EXACTLY, |
| 638 | verticalInsets, lp.height, false); |
| 639 | } |
| 640 | measureChildWithDecorationsAndMargin(view, wSpec, hSpec, true); |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | result.mConsumed = maxSize; |
| 645 | |
| 646 | int left = 0, right = 0, top = 0, bottom = 0; |
| 647 | if (mOrientation == VERTICAL) { |
| 648 | if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) { |
| 649 | bottom = layoutState.mOffset; |
| 650 | top = bottom - maxSize; |
| 651 | } else { |
| 652 | top = layoutState.mOffset; |
| 653 | bottom = top + maxSize; |
| 654 | } |
| 655 | } else { |
| 656 | if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) { |
| 657 | right = layoutState.mOffset; |
| 658 | left = right - maxSize; |
| 659 | } else { |
| 660 | left = layoutState.mOffset; |
| 661 | right = left + maxSize; |
| 662 | } |
| 663 | } |
| 664 | for (int i = 0; i < count; i++) { |
| 665 | View view = mSet[i]; |
| 666 | LayoutParams params = (LayoutParams) view.getLayoutParams(); |
| 667 | if (mOrientation == VERTICAL) { |
| 668 | if (isLayoutRTL()) { |
| 669 | right = getPaddingLeft() + mCachedBorders[mSpanCount - params.mSpanIndex]; |
| 670 | left = right - mOrientationHelper.getDecoratedMeasurementInOther(view); |
| 671 | } else { |
| 672 | left = getPaddingLeft() + mCachedBorders[params.mSpanIndex]; |
| 673 | right = left + mOrientationHelper.getDecoratedMeasurementInOther(view); |
| 674 | } |
| 675 | } else { |
| 676 | top = getPaddingTop() + mCachedBorders[params.mSpanIndex]; |
| 677 | bottom = top + mOrientationHelper.getDecoratedMeasurementInOther(view); |
| 678 | } |
| 679 | // We calculate everything with View's bounding box (which includes decor and margins) |
| 680 | // To calculate correct layout position, we subtract margins. |
| 681 | layoutDecoratedWithMargins(view, left, top, right, bottom); |
| 682 | if (DEBUG) { |
| 683 | Log.d(TAG, "laid out child at position " + getPosition(view) + ", with l:" |
| 684 | + (left + params.leftMargin) + ", t:" + (top + params.topMargin) + ", r:" |
| 685 | + (right - params.rightMargin) + ", b:" + (bottom - params.bottomMargin) |
| 686 | + ", span:" + params.mSpanIndex + ", spanSize:" + params.mSpanSize); |
| 687 | } |
| 688 | // Consume the available space if the view is not removed OR changed |
| 689 | if (params.isItemRemoved() || params.isItemChanged()) { |
| 690 | result.mIgnoreConsumed = true; |
| 691 | } |
| 692 | result.mFocusable |= view.hasFocusable(); |
| 693 | } |
| 694 | Arrays.fill(mSet, null); |
| 695 | } |
| 696 | |
| 697 | /** |
| 698 | * Measures a child with currently known information. This is not necessarily the child's final |
| 699 | * measurement. (see fillChunk for details). |
| 700 | * |
| 701 | * @param view The child view to be measured |
| 702 | * @param otherDirParentSpecMode The RV measure spec that should be used in the secondary |
| 703 | * orientation |
| 704 | * @param alreadyMeasured True if we've already measured this view once |
| 705 | */ |
| 706 | protected void measureChild(View view, int otherDirParentSpecMode, boolean alreadyMeasured) { |
| 707 | final LayoutParams lp = (LayoutParams) view.getLayoutParams(); |
| 708 | final Rect decorInsets = lp.mDecorInsets; |
| 709 | final int verticalInsets = decorInsets.top + decorInsets.bottom |
| 710 | + lp.topMargin + lp.bottomMargin; |
| 711 | final int horizontalInsets = decorInsets.left + decorInsets.right |
| 712 | + lp.leftMargin + lp.rightMargin; |
| 713 | final int availableSpaceInOther = getSpaceForSpanRange(lp.mSpanIndex, lp.mSpanSize); |
| 714 | final int wSpec; |
| 715 | final int hSpec; |
| 716 | if (mOrientation == VERTICAL) { |
| 717 | wSpec = getChildMeasureSpec(availableSpaceInOther, otherDirParentSpecMode, |
| 718 | horizontalInsets, lp.width, false); |
| 719 | hSpec = getChildMeasureSpec(mOrientationHelper.getTotalSpace(), getHeightMode(), |
| 720 | verticalInsets, lp.height, true); |
| 721 | } else { |
| 722 | hSpec = getChildMeasureSpec(availableSpaceInOther, otherDirParentSpecMode, |
| 723 | verticalInsets, lp.height, false); |
| 724 | wSpec = getChildMeasureSpec(mOrientationHelper.getTotalSpace(), getWidthMode(), |
| 725 | horizontalInsets, lp.width, true); |
| 726 | } |
| 727 | measureChildWithDecorationsAndMargin(view, wSpec, hSpec, alreadyMeasured); |
| 728 | } |
| 729 | |
| 730 | /** |
| 731 | * This is called after laying out a row (if vertical) or a column (if horizontal) when the |
| 732 | * RecyclerView does not have exact measurement specs. |
| 733 | * <p> |
| 734 | * Here we try to assign a best guess width or height and re-do the layout to update other |
| 735 | * views that wanted to MATCH_PARENT in the non-scroll orientation. |
| 736 | * |
| 737 | * @param maxSizeInOther The maximum size per span ratio from the measurement of the children. |
| 738 | * @param currentOtherDirSize The size before this layout chunk. There is no reason to go below. |
| 739 | */ |
| 740 | private void guessMeasurement(float maxSizeInOther, int currentOtherDirSize) { |
| 741 | final int contentSize = Math.round(maxSizeInOther * mSpanCount); |
| 742 | // always re-calculate because borders were stretched during the fill |
| 743 | calculateItemBorders(Math.max(contentSize, currentOtherDirSize)); |
| 744 | } |
| 745 | |
| 746 | protected void measureChildWithDecorationsAndMargin(View child, int widthSpec, int heightSpec, |
| 747 | boolean alreadyMeasured) { |
| 748 | RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) child.getLayoutParams(); |
| 749 | final boolean measure; |
| 750 | if (alreadyMeasured) { |
| 751 | measure = shouldReMeasureChild(child, widthSpec, heightSpec, lp); |
| 752 | } else { |
| 753 | measure = shouldMeasureChild(child, widthSpec, heightSpec, lp); |
| 754 | } |
| 755 | if (measure) { |
| 756 | child.measure(widthSpec, heightSpec); |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | protected void assignSpans(RecyclerView.Recycler recycler, RecyclerView.State state, int count, |
| 761 | boolean layingOutInPrimaryDirection) { |
| 762 | // spans are always assigned from 0 to N no matter if it is RTL or not. |
| 763 | // RTL is used only when positioning the view. |
| 764 | int span, start, end, diff; |
| 765 | // make sure we traverse from min position to max position |
| 766 | if (layingOutInPrimaryDirection) { |
| 767 | start = 0; |
| 768 | end = count; |
| 769 | diff = 1; |
| 770 | } else { |
| 771 | start = count - 1; |
| 772 | end = -1; |
| 773 | diff = -1; |
| 774 | } |
| 775 | span = 0; |
| 776 | for (int i = start; i != end; i += diff) { |
| 777 | View view = mSet[i]; |
| 778 | LayoutParams params = (LayoutParams) view.getLayoutParams(); |
| 779 | params.mSpanSize = getSpanSize(recycler, state, getPosition(view)); |
| 780 | params.mSpanIndex = span; |
| 781 | span += params.mSpanSize; |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | /** |
| 786 | * Returns the number of spans laid out by this grid. |
| 787 | * |
| 788 | * @return The number of spans |
| 789 | * @see #setSpanCount(int) |
| 790 | */ |
| 791 | public int getSpanCount() { |
| 792 | return mSpanCount; |
| 793 | } |
| 794 | |
| 795 | /** |
| 796 | * Sets the number of spans to be laid out. |
| 797 | * <p> |
| 798 | * If {@link #getOrientation()} is {@link #VERTICAL}, this is the number of columns. |
| 799 | * If {@link #getOrientation()} is {@link #HORIZONTAL}, this is the number of rows. |
| 800 | * |
| 801 | * @param spanCount The total number of spans in the grid |
| 802 | * @see #getSpanCount() |
| 803 | */ |
| 804 | public void setSpanCount(int spanCount) { |
| 805 | if (spanCount == mSpanCount) { |
| 806 | return; |
| 807 | } |
| 808 | mPendingSpanCountChange = true; |
| 809 | if (spanCount < 1) { |
| 810 | throw new IllegalArgumentException("Span count should be at least 1. Provided " |
| 811 | + spanCount); |
| 812 | } |
| 813 | mSpanCount = spanCount; |
| 814 | mSpanSizeLookup.invalidateSpanIndexCache(); |
| 815 | requestLayout(); |
| 816 | } |
| 817 | |
| 818 | /** |
| 819 | * A helper class to provide the number of spans each item occupies. |
| 820 | * <p> |
| 821 | * Default implementation sets each item to occupy exactly 1 span. |
| 822 | * |
| 823 | * @see GridLayoutManager#setSpanSizeLookup(SpanSizeLookup) |
| 824 | */ |
| 825 | public abstract static class SpanSizeLookup { |
| 826 | |
| 827 | final SparseIntArray mSpanIndexCache = new SparseIntArray(); |
| 828 | final SparseIntArray mSpanGroupIndexCache = new SparseIntArray(); |
| 829 | |
| 830 | private boolean mCacheSpanIndices = false; |
| 831 | private boolean mCacheSpanGroupIndices = false; |
| 832 | |
| 833 | /** |
| 834 | * Returns the number of span occupied by the item at <code>position</code>. |
| 835 | * |
| 836 | * @param position The adapter position of the item |
| 837 | * @return The number of spans occupied by the item at the provided position |
| 838 | */ |
| 839 | public abstract int getSpanSize(int position); |
| 840 | |
| 841 | /** |
| 842 | * Sets whether the results of {@link #getSpanIndex(int, int)} method should be cached or |
| 843 | * not. By default these values are not cached. If you are not overriding |
| 844 | * {@link #getSpanIndex(int, int)} with something highly performant, you should set this |
| 845 | * to true for better performance. |
| 846 | * |
| 847 | * @param cacheSpanIndices Whether results of getSpanIndex should be cached or not. |
| 848 | */ |
| 849 | public void setSpanIndexCacheEnabled(boolean cacheSpanIndices) { |
| 850 | if (!cacheSpanIndices) { |
| 851 | mSpanGroupIndexCache.clear(); |
| 852 | } |
| 853 | mCacheSpanIndices = cacheSpanIndices; |
| 854 | } |
| 855 | |
| 856 | /** |
| 857 | * Sets whether the results of {@link #getSpanGroupIndex(int, int)} method should be cached |
| 858 | * or not. By default these values are not cached. If you are not overriding |
| 859 | * {@link #getSpanGroupIndex(int, int)} with something highly performant, and you are using |
| 860 | * spans to calculate scrollbar offset and range, you should set this to true for better |
| 861 | * performance. |
| 862 | * |
| 863 | * @param cacheSpanGroupIndices Whether results of getGroupSpanIndex should be cached or |
| 864 | * not. |
| 865 | */ |
| 866 | public void setSpanGroupIndexCacheEnabled(boolean cacheSpanGroupIndices) { |
| 867 | if (!cacheSpanGroupIndices) { |
| 868 | mSpanGroupIndexCache.clear(); |
| 869 | } |
| 870 | mCacheSpanGroupIndices = cacheSpanGroupIndices; |
| 871 | } |
| 872 | |
| 873 | /** |
| 874 | * Clears the span index cache. GridLayoutManager automatically calls this method when |
| 875 | * adapter changes occur. |
| 876 | */ |
| 877 | public void invalidateSpanIndexCache() { |
| 878 | mSpanIndexCache.clear(); |
| 879 | } |
| 880 | |
| 881 | /** |
| 882 | * Clears the span group index cache. GridLayoutManager automatically calls this method |
| 883 | * when adapter changes occur. |
| 884 | */ |
| 885 | public void invalidateSpanGroupIndexCache() { |
| 886 | mSpanGroupIndexCache.clear(); |
| 887 | } |
| 888 | |
| 889 | /** |
| 890 | * Returns whether results of {@link #getSpanIndex(int, int)} method are cached or not. |
| 891 | * |
| 892 | * @return True if results of {@link #getSpanIndex(int, int)} are cached. |
| 893 | */ |
| 894 | public boolean isSpanIndexCacheEnabled() { |
| 895 | return mCacheSpanIndices; |
| 896 | } |
| 897 | |
| 898 | /** |
| 899 | * Returns whether results of {@link #getSpanGroupIndex(int, int)} method are cached or not. |
| 900 | * |
| 901 | * @return True if results of {@link #getSpanGroupIndex(int, int)} are cached. |
| 902 | */ |
| 903 | public boolean isSpanGroupIndexCacheEnabled() { |
| 904 | return mCacheSpanGroupIndices; |
| 905 | } |
| 906 | |
| 907 | int getCachedSpanIndex(int position, int spanCount) { |
| 908 | if (!mCacheSpanIndices) { |
| 909 | return getSpanIndex(position, spanCount); |
| 910 | } |
| 911 | final int existing = mSpanIndexCache.get(position, -1); |
| 912 | if (existing != -1) { |
| 913 | return existing; |
| 914 | } |
| 915 | final int value = getSpanIndex(position, spanCount); |
| 916 | mSpanIndexCache.put(position, value); |
| 917 | return value; |
| 918 | } |
| 919 | |
| 920 | int getCachedSpanGroupIndex(int position, int spanCount) { |
| 921 | if (!mCacheSpanGroupIndices) { |
| 922 | return getSpanGroupIndex(position, spanCount); |
| 923 | } |
| 924 | final int existing = mSpanGroupIndexCache.get(position, -1); |
| 925 | if (existing != -1) { |
| 926 | return existing; |
| 927 | } |
| 928 | final int value = getSpanGroupIndex(position, spanCount); |
| 929 | mSpanGroupIndexCache.put(position, value); |
| 930 | return value; |
| 931 | } |
| 932 | |
| 933 | /** |
| 934 | * Returns the final span index of the provided position. |
| 935 | * <p> |
| 936 | * If you have a faster way to calculate span index for your items, you should override |
| 937 | * this method. Otherwise, you should enable span index cache |
| 938 | * ({@link #setSpanIndexCacheEnabled(boolean)}) for better performance. When caching is |
| 939 | * disabled, default implementation traverses all items from 0 to |
| 940 | * <code>position</code>. When caching is enabled, it calculates from the closest cached |
| 941 | * value before the <code>position</code>. |
| 942 | * <p> |
| 943 | * If you override this method, you need to make sure it is consistent with |
| 944 | * {@link #getSpanSize(int)}. GridLayoutManager does not call this method for |
| 945 | * each item. It is called only for the reference item and rest of the items |
| 946 | * are assigned to spans based on the reference item. For example, you cannot assign a |
| 947 | * position to span 2 while span 1 is empty. |
| 948 | * <p> |
| 949 | * Note that span offsets always start with 0 and are not affected by RTL. |
| 950 | * |
| 951 | * @param position The position of the item |
| 952 | * @param spanCount The total number of spans in the grid |
| 953 | * @return The final span position of the item. Should be between 0 (inclusive) and |
| 954 | * <code>spanCount</code>(exclusive) |
| 955 | */ |
| 956 | public int getSpanIndex(int position, int spanCount) { |
| 957 | int positionSpanSize = getSpanSize(position); |
| 958 | if (positionSpanSize == spanCount) { |
| 959 | return 0; // quick return for full-span items |
| 960 | } |
| 961 | int span = 0; |
| 962 | int startPos = 0; |
| 963 | // If caching is enabled, try to jump |
| 964 | if (mCacheSpanIndices) { |
| 965 | int prevKey = findFirstKeyLessThan(mSpanIndexCache, position); |
| 966 | if (prevKey >= 0) { |
| 967 | span = mSpanIndexCache.get(prevKey) + getSpanSize(prevKey); |
| 968 | startPos = prevKey + 1; |
| 969 | } |
| 970 | } |
| 971 | for (int i = startPos; i < position; i++) { |
| 972 | int size = getSpanSize(i); |
| 973 | span += size; |
| 974 | if (span == spanCount) { |
| 975 | span = 0; |
| 976 | } else if (span > spanCount) { |
| 977 | // did not fit, moving to next row / column |
| 978 | span = size; |
| 979 | } |
| 980 | } |
| 981 | if (span + positionSpanSize <= spanCount) { |
| 982 | return span; |
| 983 | } |
| 984 | return 0; |
| 985 | } |
| 986 | |
| 987 | static int findFirstKeyLessThan(SparseIntArray cache, int position) { |
| 988 | int lo = 0; |
| 989 | int hi = cache.size() - 1; |
| 990 | |
| 991 | while (lo <= hi) { |
| 992 | // Using unsigned shift here to divide by two because it is guaranteed to not |
| 993 | // overflow. |
| 994 | final int mid = (lo + hi) >>> 1; |
| 995 | final int midVal = cache.keyAt(mid); |
| 996 | if (midVal < position) { |
| 997 | lo = mid + 1; |
| 998 | } else { |
| 999 | hi = mid - 1; |
| 1000 | } |
| 1001 | } |
| 1002 | int index = lo - 1; |
| 1003 | if (index >= 0 && index < cache.size()) { |
| 1004 | return cache.keyAt(index); |
| 1005 | } |
| 1006 | return -1; |
| 1007 | } |
| 1008 | |
| 1009 | /** |
| 1010 | * Returns the index of the group this position belongs. |
| 1011 | * <p> |
| 1012 | * For example, if grid has 3 columns and each item occupies 1 span, span group index |
| 1013 | * for item 1 will be 0, item 5 will be 1. |
| 1014 | * |
| 1015 | * @param adapterPosition The position in adapter |
| 1016 | * @param spanCount The total number of spans in the grid |
| 1017 | * @return The index of the span group including the item at the given adapter position |
| 1018 | */ |
| 1019 | public int getSpanGroupIndex(int adapterPosition, int spanCount) { |
| 1020 | int span = 0; |
| 1021 | int group = 0; |
| 1022 | int start = 0; |
| 1023 | if (mCacheSpanGroupIndices) { |
| 1024 | // This finds the first non empty cached group cache key. |
| 1025 | int prevKey = findFirstKeyLessThan(mSpanGroupIndexCache, adapterPosition); |
| 1026 | if (prevKey != -1) { |
| 1027 | group = mSpanGroupIndexCache.get(prevKey); |
| 1028 | start = prevKey + 1; |
| 1029 | span = getCachedSpanIndex(prevKey, spanCount) + getSpanSize(prevKey); |
| 1030 | if (span == spanCount) { |
| 1031 | span = 0; |
| 1032 | group++; |
| 1033 | } |
| 1034 | } |
| 1035 | } |
| 1036 | int positionSpanSize = getSpanSize(adapterPosition); |
| 1037 | for (int i = start; i < adapterPosition; i++) { |
| 1038 | int size = getSpanSize(i); |
| 1039 | span += size; |
| 1040 | if (span == spanCount) { |
| 1041 | span = 0; |
| 1042 | group++; |
| 1043 | } else if (span > spanCount) { |
| 1044 | // did not fit, moving to next row / column |
| 1045 | span = size; |
| 1046 | group++; |
| 1047 | } |
| 1048 | } |
| 1049 | if (span + positionSpanSize > spanCount) { |
| 1050 | group++; |
| 1051 | } |
| 1052 | return group; |
| 1053 | } |
| 1054 | } |
| 1055 | |
| 1056 | @Override |
| 1057 | public View onFocusSearchFailed(View focused, int focusDirection, |
| 1058 | RecyclerView.Recycler recycler, RecyclerView.State state) { |
| 1059 | View prevFocusedChild = findContainingItemView(focused); |
| 1060 | if (prevFocusedChild == null) { |
| 1061 | return null; |
| 1062 | } |
| 1063 | LayoutParams lp = (LayoutParams) prevFocusedChild.getLayoutParams(); |
| 1064 | final int prevSpanStart = lp.mSpanIndex; |
| 1065 | final int prevSpanEnd = lp.mSpanIndex + lp.mSpanSize; |
| 1066 | View view = super.onFocusSearchFailed(focused, focusDirection, recycler, state); |
| 1067 | if (view == null) { |
| 1068 | return null; |
| 1069 | } |
| 1070 | // LinearLayoutManager finds the last child. What we want is the child which has the same |
| 1071 | // spanIndex. |
| 1072 | final int layoutDir = convertFocusDirectionToLayoutDirection(focusDirection); |
| 1073 | final boolean ascend = (layoutDir == LayoutState.LAYOUT_END) != mShouldReverseLayout; |
| 1074 | final int start, inc, limit; |
| 1075 | if (ascend) { |
| 1076 | start = getChildCount() - 1; |
| 1077 | inc = -1; |
| 1078 | limit = -1; |
| 1079 | } else { |
| 1080 | start = 0; |
| 1081 | inc = 1; |
| 1082 | limit = getChildCount(); |
| 1083 | } |
| 1084 | final boolean preferLastSpan = mOrientation == VERTICAL && isLayoutRTL(); |
| 1085 | |
| 1086 | // The focusable candidate to be picked if no perfect focusable candidate is found. |
| 1087 | // The best focusable candidate is the one with the highest amount of span overlap with |
| 1088 | // the currently focused view. |
| 1089 | View focusableWeakCandidate = null; // somewhat matches but not strong |
| 1090 | int focusableWeakCandidateSpanIndex = -1; |
| 1091 | int focusableWeakCandidateOverlap = 0; // how many spans overlap |
| 1092 | |
| 1093 | // The unfocusable candidate to become visible on the screen next, if no perfect or |
| 1094 | // weak focusable candidates are found to receive focus next. |
| 1095 | // We are only interested in partially visible unfocusable views. These are views that are |
| 1096 | // not fully visible, that is either partially overlapping, or out-of-bounds and right below |
| 1097 | // or above RV's padded bounded area. The best unfocusable candidate is the one with the |
| 1098 | // highest amount of span overlap with the currently focused view. |
| 1099 | View unfocusableWeakCandidate = null; // somewhat matches but not strong |
| 1100 | int unfocusableWeakCandidateSpanIndex = -1; |
| 1101 | int unfocusableWeakCandidateOverlap = 0; // how many spans overlap |
| 1102 | |
| 1103 | // The span group index of the start child. This indicates the span group index of the |
| 1104 | // next focusable item to receive focus, if a focusable item within the same span group |
| 1105 | // exists. Any focusable item beyond this group index are not relevant since they |
| 1106 | // were already stored in the layout before onFocusSearchFailed call and were not picked |
| 1107 | // by the focusSearch algorithm. |
| 1108 | int focusableSpanGroupIndex = getSpanGroupIndex(recycler, state, start); |
| 1109 | for (int i = start; i != limit; i += inc) { |
| 1110 | int spanGroupIndex = getSpanGroupIndex(recycler, state, i); |
| 1111 | View candidate = getChildAt(i); |
| 1112 | if (candidate == prevFocusedChild) { |
| 1113 | break; |
| 1114 | } |
| 1115 | |
| 1116 | if (candidate.hasFocusable() && spanGroupIndex != focusableSpanGroupIndex) { |
| 1117 | // We are past the allowable span group index for the next focusable item. |
| 1118 | // The search only continues if no focusable weak candidates have been found up |
| 1119 | // until this point, in order to find the best unfocusable candidate to become |
| 1120 | // visible on the screen next. |
| 1121 | if (focusableWeakCandidate != null) { |
| 1122 | break; |
| 1123 | } |
| 1124 | continue; |
| 1125 | } |
| 1126 | |
| 1127 | final LayoutParams candidateLp = (LayoutParams) candidate.getLayoutParams(); |
| 1128 | final int candidateStart = candidateLp.mSpanIndex; |
| 1129 | final int candidateEnd = candidateLp.mSpanIndex + candidateLp.mSpanSize; |
| 1130 | if (candidate.hasFocusable() && candidateStart == prevSpanStart |
| 1131 | && candidateEnd == prevSpanEnd) { |
| 1132 | return candidate; // perfect match |
| 1133 | } |
| 1134 | boolean assignAsWeek = false; |
| 1135 | if ((candidate.hasFocusable() && focusableWeakCandidate == null) |
| 1136 | || (!candidate.hasFocusable() && unfocusableWeakCandidate == null)) { |
| 1137 | assignAsWeek = true; |
| 1138 | } else { |
| 1139 | int maxStart = Math.max(candidateStart, prevSpanStart); |
| 1140 | int minEnd = Math.min(candidateEnd, prevSpanEnd); |
| 1141 | int overlap = minEnd - maxStart; |
| 1142 | if (candidate.hasFocusable()) { |
| 1143 | if (overlap > focusableWeakCandidateOverlap) { |
| 1144 | assignAsWeek = true; |
| 1145 | } else if (overlap == focusableWeakCandidateOverlap |
| 1146 | && preferLastSpan == (candidateStart |
| 1147 | > focusableWeakCandidateSpanIndex)) { |
| 1148 | assignAsWeek = true; |
| 1149 | } |
| 1150 | } else if (focusableWeakCandidate == null |
| 1151 | && isViewPartiallyVisible(candidate, false, true)) { |
| 1152 | if (overlap > unfocusableWeakCandidateOverlap) { |
| 1153 | assignAsWeek = true; |
| 1154 | } else if (overlap == unfocusableWeakCandidateOverlap |
| 1155 | && preferLastSpan == (candidateStart |
| 1156 | > unfocusableWeakCandidateSpanIndex)) { |
| 1157 | assignAsWeek = true; |
| 1158 | } |
| 1159 | } |
| 1160 | } |
| 1161 | |
| 1162 | if (assignAsWeek) { |
| 1163 | if (candidate.hasFocusable()) { |
| 1164 | focusableWeakCandidate = candidate; |
| 1165 | focusableWeakCandidateSpanIndex = candidateLp.mSpanIndex; |
| 1166 | focusableWeakCandidateOverlap = Math.min(candidateEnd, prevSpanEnd) |
| 1167 | - Math.max(candidateStart, prevSpanStart); |
| 1168 | } else { |
| 1169 | unfocusableWeakCandidate = candidate; |
| 1170 | unfocusableWeakCandidateSpanIndex = candidateLp.mSpanIndex; |
| 1171 | unfocusableWeakCandidateOverlap = Math.min(candidateEnd, prevSpanEnd) |
| 1172 | - Math.max(candidateStart, prevSpanStart); |
| 1173 | } |
| 1174 | } |
| 1175 | } |
| 1176 | return (focusableWeakCandidate != null) ? focusableWeakCandidate : unfocusableWeakCandidate; |
| 1177 | } |
| 1178 | |
| 1179 | @Override |
| 1180 | public boolean supportsPredictiveItemAnimations() { |
| 1181 | return mPendingSavedState == null && !mPendingSpanCountChange; |
| 1182 | } |
| 1183 | |
| 1184 | @Override |
| 1185 | public int computeHorizontalScrollRange(RecyclerView.State state) { |
| 1186 | if (mUsingSpansToEstimateScrollBarDimensions) { |
| 1187 | return computeScrollRangeWithSpanInfo(state); |
| 1188 | } else { |
| 1189 | return super.computeHorizontalScrollRange(state); |
| 1190 | } |
| 1191 | } |
| 1192 | |
| 1193 | @Override |
| 1194 | public int computeVerticalScrollRange(RecyclerView.State state) { |
| 1195 | if (mUsingSpansToEstimateScrollBarDimensions) { |
| 1196 | return computeScrollRangeWithSpanInfo(state); |
| 1197 | } else { |
| 1198 | return super.computeVerticalScrollRange(state); |
| 1199 | } |
| 1200 | } |
| 1201 | |
| 1202 | @Override |
| 1203 | public int computeHorizontalScrollOffset(RecyclerView.State state) { |
| 1204 | if (mUsingSpansToEstimateScrollBarDimensions) { |
| 1205 | return computeScrollOffsetWithSpanInfo(state); |
| 1206 | } else { |
| 1207 | return super.computeHorizontalScrollOffset(state); |
| 1208 | } |
| 1209 | } |
| 1210 | |
| 1211 | @Override |
| 1212 | public int computeVerticalScrollOffset(RecyclerView.State state) { |
| 1213 | if (mUsingSpansToEstimateScrollBarDimensions) { |
| 1214 | return computeScrollOffsetWithSpanInfo(state); |
| 1215 | } else { |
| 1216 | return super.computeVerticalScrollOffset(state); |
| 1217 | } |
| 1218 | } |
| 1219 | |
| 1220 | /** |
| 1221 | * When this flag is set, the scroll offset and scroll range calculations will take account |
| 1222 | * of span information. |
| 1223 | * |
| 1224 | * <p>This is will increase the accuracy of the scroll bar's size and offset but will require |
| 1225 | * more calls to {@link SpanSizeLookup#getSpanGroupIndex(int, int)}". |
| 1226 | * |
| 1227 | * <p>This additional accuracy may or may not be needed, depending on the characteristics of |
| 1228 | * your layout. You will likely benefit from this accuracy when: |
| 1229 | * |
| 1230 | * <ul> |
| 1231 | * <li>The variation in item span sizes is large. |
| 1232 | * <li>The size of your data set is small (if your data set is large, the scrollbar will |
| 1233 | * likely be very small anyway, and thus the increased accuracy has less impact). |
| 1234 | * <li>Calls to {@link SpanSizeLookup#getSpanGroupIndex(int, int)} are fast. |
| 1235 | * </ul> |
| 1236 | * |
| 1237 | * <p>If you decide to enable this feature, you should be sure that calls to |
| 1238 | * {@link SpanSizeLookup#getSpanGroupIndex(int, int)} are fast, that set span group index |
| 1239 | * caching is set to true via a call to |
| 1240 | * {@link SpanSizeLookup#setSpanGroupIndexCacheEnabled(boolean), |
| 1241 | * and span index caching is also enabled via a call to |
| 1242 | * {@link SpanSizeLookup#setSpanIndexCacheEnabled(boolean)}}. |
| 1243 | */ |
| 1244 | public void setUsingSpansToEstimateScrollbarDimensions( |
| 1245 | boolean useSpansToEstimateScrollBarDimensions) { |
| 1246 | mUsingSpansToEstimateScrollBarDimensions = useSpansToEstimateScrollBarDimensions; |
| 1247 | } |
| 1248 | |
| 1249 | /** |
| 1250 | * Returns true if the scroll offset and scroll range calculations take account of span |
| 1251 | * information. See {@link #setUsingSpansToEstimateScrollbarDimensions(boolean)} for more |
| 1252 | * information on this topic. Defaults to {@code false}. |
| 1253 | * |
| 1254 | * @return true if the scroll offset and scroll range calculations take account of span |
| 1255 | * information. |
| 1256 | */ |
| 1257 | public boolean isUsingSpansToEstimateScrollbarDimensions() { |
| 1258 | return mUsingSpansToEstimateScrollBarDimensions; |
| 1259 | } |
| 1260 | |
| 1261 | private int computeScrollRangeWithSpanInfo(RecyclerView.State state) { |
| 1262 | if (getChildCount() == 0 || state.getItemCount() == 0) { |
| 1263 | return 0; |
| 1264 | } |
| 1265 | ensureLayoutState(); |
| 1266 | |
| 1267 | View startChild = findFirstVisibleChildClosestToStart(!isSmoothScrollbarEnabled(), true); |
| 1268 | View endChild = findFirstVisibleChildClosestToEnd(!isSmoothScrollbarEnabled(), true); |
| 1269 | |
| 1270 | if (startChild == null || endChild == null) { |
| 1271 | return 0; |
| 1272 | } |
| 1273 | if (!isSmoothScrollbarEnabled()) { |
| 1274 | return mSpanSizeLookup.getCachedSpanGroupIndex( |
| 1275 | state.getItemCount() - 1, mSpanCount) + 1; |
| 1276 | } |
| 1277 | |
| 1278 | // smooth scrollbar enabled. try to estimate better. |
| 1279 | final int laidOutArea = mOrientationHelper.getDecoratedEnd(endChild) |
| 1280 | - mOrientationHelper.getDecoratedStart(startChild); |
| 1281 | |
| 1282 | final int firstVisibleSpan = |
| 1283 | mSpanSizeLookup.getCachedSpanGroupIndex(getPosition(startChild), mSpanCount); |
| 1284 | final int lastVisibleSpan = mSpanSizeLookup.getCachedSpanGroupIndex(getPosition(endChild), |
| 1285 | mSpanCount); |
| 1286 | final int totalSpans = mSpanSizeLookup.getCachedSpanGroupIndex(state.getItemCount() - 1, |
| 1287 | mSpanCount) + 1; |
| 1288 | final int laidOutSpans = lastVisibleSpan - firstVisibleSpan + 1; |
| 1289 | |
| 1290 | // estimate a size for full list. |
| 1291 | return (int) (((float) laidOutArea / laidOutSpans) * totalSpans); |
| 1292 | } |
| 1293 | |
| 1294 | private int computeScrollOffsetWithSpanInfo(RecyclerView.State state) { |
| 1295 | if (getChildCount() == 0 || state.getItemCount() == 0) { |
| 1296 | return 0; |
| 1297 | } |
| 1298 | ensureLayoutState(); |
| 1299 | |
| 1300 | boolean smoothScrollEnabled = isSmoothScrollbarEnabled(); |
| 1301 | View startChild = findFirstVisibleChildClosestToStart(!smoothScrollEnabled, true); |
| 1302 | View endChild = findFirstVisibleChildClosestToEnd(!smoothScrollEnabled, true); |
| 1303 | if (startChild == null || endChild == null) { |
| 1304 | return 0; |
| 1305 | } |
| 1306 | int startChildSpan = mSpanSizeLookup.getCachedSpanGroupIndex(getPosition(startChild), |
| 1307 | mSpanCount); |
| 1308 | int endChildSpan = mSpanSizeLookup.getCachedSpanGroupIndex(getPosition(endChild), |
| 1309 | mSpanCount); |
| 1310 | |
| 1311 | final int minSpan = Math.min(startChildSpan, endChildSpan); |
| 1312 | final int maxSpan = Math.max(startChildSpan, endChildSpan); |
| 1313 | final int totalSpans = mSpanSizeLookup.getCachedSpanGroupIndex(state.getItemCount() - 1, |
| 1314 | mSpanCount) + 1; |
| 1315 | |
| 1316 | final int spansBefore = mShouldReverseLayout |
| 1317 | ? Math.max(0, totalSpans - maxSpan - 1) |
| 1318 | : Math.max(0, minSpan); |
| 1319 | if (!smoothScrollEnabled) { |
| 1320 | return spansBefore; |
| 1321 | } |
| 1322 | final int laidOutArea = Math.abs(mOrientationHelper.getDecoratedEnd(endChild) |
| 1323 | - mOrientationHelper.getDecoratedStart(startChild)); |
| 1324 | |
| 1325 | final int firstVisibleSpan = |
| 1326 | mSpanSizeLookup.getCachedSpanGroupIndex(getPosition(startChild), mSpanCount); |
| 1327 | final int lastVisibleSpan = mSpanSizeLookup.getCachedSpanGroupIndex(getPosition(endChild), |
| 1328 | mSpanCount); |
| 1329 | final int laidOutSpans = lastVisibleSpan - firstVisibleSpan + 1; |
| 1330 | final float avgSizePerSpan = (float) laidOutArea / laidOutSpans; |
| 1331 | |
| 1332 | return Math.round(spansBefore * avgSizePerSpan + (mOrientationHelper.getStartAfterPadding() |
| 1333 | - mOrientationHelper.getDecoratedStart(startChild))); |
| 1334 | } |
| 1335 | |
| 1336 | /** |
| 1337 | * Default implementation for {@link SpanSizeLookup}. Each item occupies 1 span. |
| 1338 | */ |
| 1339 | public static final class DefaultSpanSizeLookup extends SpanSizeLookup { |
| 1340 | |
| 1341 | @Override |
| 1342 | public int getSpanSize(int position) { |
| 1343 | return 1; |
| 1344 | } |
| 1345 | |
| 1346 | @Override |
| 1347 | public int getSpanIndex(int position, int spanCount) { |
| 1348 | return position % spanCount; |
| 1349 | } |
| 1350 | } |
| 1351 | |
| 1352 | /** |
| 1353 | * LayoutParams used by GridLayoutManager. |
| 1354 | * <p> |
| 1355 | * Note that if the orientation is {@link #VERTICAL}, the width parameter is ignored and if the |
| 1356 | * orientation is {@link #HORIZONTAL} the height parameter is ignored because child view is |
| 1357 | * expected to fill all of the space given to it. |
| 1358 | */ |
| 1359 | public static class LayoutParams extends RecyclerView.LayoutParams { |
| 1360 | |
| 1361 | /** |
| 1362 | * Span Id for Views that are not laid out yet. |
| 1363 | */ |
| 1364 | public static final int INVALID_SPAN_ID = -1; |
| 1365 | |
| 1366 | int mSpanIndex = INVALID_SPAN_ID; |
| 1367 | |
| 1368 | public int mSpanSize = 0; |
| 1369 | |
| 1370 | public LayoutParams(Context c, AttributeSet attrs) { |
| 1371 | super(c, attrs); |
| 1372 | } |
| 1373 | |
| 1374 | public LayoutParams(int width, int height) { |
| 1375 | super(width, height); |
| 1376 | } |
| 1377 | |
| 1378 | public LayoutParams(ViewGroup.MarginLayoutParams source) { |
| 1379 | super(source); |
| 1380 | } |
| 1381 | |
| 1382 | public LayoutParams(ViewGroup.LayoutParams source) { |
| 1383 | super(source); |
| 1384 | } |
| 1385 | |
| 1386 | public LayoutParams(RecyclerView.LayoutParams source) { |
| 1387 | super(source); |
| 1388 | } |
| 1389 | |
| 1390 | /** |
| 1391 | * Returns the current span index of this View. If the View is not laid out yet, the return |
| 1392 | * value is <code>undefined</code>. |
| 1393 | * <p> |
| 1394 | * Starting with RecyclerView <b>24.2.0</b>, span indices are always indexed from position 0 |
| 1395 | * even if the layout is RTL. In a vertical GridLayoutManager, <b>leftmost</b> span is span |
| 1396 | * 0 if the layout is <b>LTR</b> and <b>rightmost</b> span is span 0 if the layout is |
| 1397 | * <b>RTL</b>. Prior to 24.2.0, it was the opposite which was conflicting with |
| 1398 | * {@link SpanSizeLookup#getSpanIndex(int, int)}. |
| 1399 | * <p> |
| 1400 | * If the View occupies multiple spans, span with the minimum index is returned. |
| 1401 | * |
| 1402 | * @return The span index of the View. |
| 1403 | */ |
| 1404 | public int getSpanIndex() { |
| 1405 | return mSpanIndex; |
| 1406 | } |
| 1407 | |
| 1408 | /** |
| 1409 | * Returns the number of spans occupied by this View. If the View not laid out yet, the |
| 1410 | * return value is <code>undefined</code>. |
| 1411 | * |
| 1412 | * @return The number of spans occupied by this View. |
| 1413 | */ |
| 1414 | public int getSpanSize() { |
| 1415 | return mSpanSize; |
| 1416 | } |
| 1417 | } |
| 1418 | |
| 1419 | } |
| 1420 | |