RecyclerView 根据滑动位置动态改变背景透明度

RecyclerView 根据滑动位置动态改变背景透明度

根据滑动位置动态改变背景透明度,直接上代码:

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
binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
onRecyclerScrolled(recyclerView, dx, dy)
}

override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
}
})

private val dp180 = dp2px(180)
private var distanceY = 0
private var current = 0
private fun onRecyclerScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
distanceY += dy
when {
distanceY >= dp180 -> {
if (current == 1) return
recyclerView.setBackgroundColor(Color.argb(255, 246, 248, 250))
current = 1
}
distanceY <= 0 -> {
if (current == 0) return
recyclerView.setBackgroundColor(Color.argb(0, 246, 248, 250))
current = 0
}
else -> {
recyclerView.setBackgroundColor(
Color.argb(
distanceY * 255 / dp180,
246, 248, 250
)
)
current = -1
}
}
}
作者

Dench

发布于

2022-06-27

更新于

2022-06-27

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×