BaseQuickRecycleViewAdapter自动大小

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
fun RecyclerView.setItemCount(
columns: Int,
rows: Int
) {
if (adapter != null && adapter is BaseListAdapter<*, *>) {
(adapter as BaseListAdapter<*, *>).width = width / columns
(adapter as BaseListAdapter<*, *>).height = height / rows
}
}

inline fun RecyclerView.waitForLayout(crossinline f: () -> Unit) = with(viewTreeObserver) {
addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
removeOnGlobalLayoutListener(this)
f()
}
})
}

inline fun RecyclerView.waitForLayout2(crossinline f: () -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
viewTreeObserver.removeOnGlobalLayoutListener(this)
f()
}
})
}

// 最终还是这个好用
inline fun RecyclerView.waitForLayout3(crossinline f: () -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (measuredWidth > 0 && measuredHeight > 0) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
f()
if (adapter != null && adapter is BaseListAdapter<*, *>) {
(adapter as BaseListAdapter<*, *>).width = width / 10
(adapter as BaseListAdapter<*, *>).height = height / 1
(adapter as BaseListAdapter<*, *>).notifyDataSetChanged()
}
}
}
})
}

inline fun <T: View> T.afterMeasured(crossinline f: T.() -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (measuredWidth > 0 && measuredHeight > 0) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
f()
}
}
})
}