recycleView(三)动态修改背景色

效果图
recycleView(三)动态修改背景色_第1张图片
recycleView(三)动态修改背景色_第2张图片

1.关键代码

1.

        // 定义一个变量来记录滑动的距离
        var scrollDistance = 0
        // 在RecycleView的滑动监听器中更新滑动的距离
        binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                // 累加滑动的距离
                scrollDistance += dy
                // 根据滑动的距离设置背景颜色
                if (scrollDistance > 100) {
                    binding.button.setBackgroundColor(Color.GRAY)
                    recyclerView.setBackgroundColor(Color.GRAY)
                } else {
                    binding.button.setBackgroundColor(Color.WHITE)
                    recyclerView.setBackgroundColor(Color.WHITE)
                }
            }
        })

3.总结

1.

你可能感兴趣的:(android)