-
Notifications
You must be signed in to change notification settings - Fork 464
Expand file tree
/
Copy pathSafeLinearLayoutManager.kt
More file actions
70 lines (63 loc) · 2.76 KB
/
SafeLinearLayoutManager.kt
File metadata and controls
70 lines (63 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.reactnativepagerview
import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
/**
* A LinearLayoutManager that catches the "Scrapped or attached views may not be recycled"
* IllegalArgumentException thrown by RecyclerView during scroll-based recycling.
*
* This crash occurs when RecyclerView's internal removeAndRecycleViewAt calls removeViewAt
* to detach a view, but the view's mParent remains non-null (e.g. due to the view being
* held as a "disappearing view" by ViewGroup). The subsequent recycleViewHolderInternal
* check throws because holder.itemView.getParent() != null.
*
* Since this only happens during teardown (back navigation while mid-scroll), catching
* the exception and aborting the scroll is safe — the view is being destroyed anyway.
*/
class SafeLinearLayoutManager(
context: Context,
private val viewPager: ViewPager2
) : LinearLayoutManager(context) {
override fun calculateExtraLayoutSpace(state: RecyclerView.State, extraLayoutSpace: IntArray) {
val pageLimit = viewPager.offscreenPageLimit
if (pageLimit == ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT) {
super.calculateExtraLayoutSpace(state, extraLayoutSpace)
extraLayoutSpace[0] = extraLayoutSpace[0].coerceAtLeast(getPageSize())
extraLayoutSpace[1] = extraLayoutSpace[1].coerceAtLeast(getPageSize())
} else {
val offscreenSpace = getPageSize() * pageLimit
extraLayoutSpace[0] = offscreenSpace
extraLayoutSpace[1] = offscreenSpace
}
}
private fun getPageSize(): Int {
val rv = viewPager.getChildAt(0) as? RecyclerView ?: return 0
return if (orientation == HORIZONTAL) {
rv.width - rv.paddingLeft - rv.paddingRight
} else {
rv.height - rv.paddingTop - rv.paddingBottom
}
}
override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int {
return try {
super.scrollHorizontallyBy(dx, recycler, state)
} catch (_: IllegalArgumentException) {
0
}
}
override fun scrollVerticallyBy(dy: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int {
return try {
super.scrollVerticallyBy(dy, recycler, state)
} catch (_: IllegalArgumentException) {
0
}
}
override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) {
try {
super.onLayoutChildren(recycler, state)
} catch (_: IllegalArgumentException) {
// View is being torn down, layout will not be needed again
}
}
}