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