解决SwipeRefreshLayout和RecyclerView时滑动冲突
# 问题复现
SwipeRefreshLayout嵌套RecyclerView,当内容超过屏幕下拉,不知道你是要下拉刷新还是下滑,一直认为你是下拉刷新。
【问题伪代码】
class LogoActivity : AppCompatActivity() {
private lateinit var binding: ActivityLogoBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLogoBinding.inflate(layoutInflater)
setContentView(binding.root)
// 初始化xml控件
mRecyclerView = binding.mRecyclerView
mRefreshLayout = binding.refreshLayout
onPullRefresh()
onLoadMore()
}
/**
* 下拉刷新
*/
private fun onPullRefresh() {
mRefreshLayout.setColorSchemeColors(Color.parseColor("#03A9F4"))
mRefreshLayout.setOnRefreshListener {
thread {
Thread.sleep(700) // 这个延迟0.7秒只是为了实现视觉效果,与逻辑无关
runOnUiThread {
loadNewData()
mRefreshLayout.isRefreshing = false // 让圆形进度条停下来
}
}
}
}
private fun onLoadMore() {
// 设置加载更多监听
mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
val manager = recyclerView.layoutManager as LinearLayoutManager
if (manager != null) {
// 当不滑动时
when (newState) {
RecyclerView.SCROLL_STATE_IDLE -> {
loadNewData()
}
RecyclerView.SCROLL_STATE_DRAGGING -> {}
RecyclerView.SCROLL_STATE_SETTLING -> {}
else -> {}
}
}
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
// TODO: 在此处解决滑动冲突
}
})
}
}
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
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
# 解决方式
在1上述TODO处添加代码
mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val topRowVerticalPosition =
if (recyclerView == null || recyclerView.childCount === 0)
0 else recyclerView.getChildAt(0).top
// 大于0表示正在向上滑动,小于等于0表示停止或向下滑动
mRefreshLayout.isEnabled = topRowVerticalPosition >= 0
}
})
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
添加好后,再测试一下就可以正常滑动了!
编辑 (opens new window)
上次更新: 2022/07/02, 23:36:04