要实现水平自动循环滚动的 RecyclerView,可以使用 BaseRecyclerViewAdapterHelper 库来简化操作。下面是实现该功能的步骤:

  1. build.gradle 文件中添加 BaseRecyclerViewAdapterHelper 库的依赖:
implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.10'
  1. 创建一个自定义的 LayoutManager 类,继承自 LinearLayoutManager,并重写 scrollHorizontallyBy() 方法来实现循环滚动的效果:
class LoopLinearLayoutManager(context: Context) : LinearLayoutManager(context) {

    override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler?, state: RecyclerView.State?): Int {
        val orientation = orientation
        val scrolled = super.scrollHorizontallyBy(dx, recycler, state)
        if (itemCount > 0) {
            val childWidth = getChildAt(0)?.width ?: 0
            val childCount = childCount
            val firstChild = getChildAt(0)
            val lastChild = getChildAt(childCount - 1)

            if (orientation == HORIZONTAL) {
                if (scrolled > 0 && getPosition(firstChild!!) == 0) {
                    val left = firstChild.left - dx
                    if (left > 0) {
                        val newDx = -dx + left
                        return -newDx
                    }
                } else if (scrolled < 0 && getPosition(lastChild!!) == itemCount - 1) {
                    val right = lastChild.right - dx
                    if (right < width) {
                        val newDx = dx - (width - right)
                        return -newDx
                    }
                }
            }
        }
        return scrolled
    }
}
  1. 创建一个自定义的 BaseQuickAdapter 类,继承自 BaseQuickAdapter,并在 convert() 方法中设置点击事件:
class MyAdapter(data: List<String>) : BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_layout, data) {

    override fun convert(holder: BaseViewHolder, item: String) {
        holder.setText(R.id.tv_item, item)

        holder.itemView.setOnClickListener {
            // 处理点击事件
        }
    }
}
  1. 在 Activity 或 Fragment 中使用 RecyclerView,并设置 LayoutManager 和 Adapter:
val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
val layoutManager = LoopLinearLayoutManager(this)
layoutManager.orientation = LinearLayoutManager.HORIZONTAL
recyclerView.layoutManager = layoutManager

val adapter = MyAdapter(dataList)
recyclerView.adapter = adapter

这样就可以实现水平自动循环滚动的 RecyclerView 了。当滚动时,可以通过触摸停止滚动,松开后会继续滚动。同时,通过点击 RecyclerView 的 item 也可以处理点击事件。

Android Kotlin RecyclerView 实现水平自动循环滚动 - 使用 BaseRecyclerViewAdapterHelper

原文地址: http://www.cveoy.top/t/topic/bnm5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录