首页 > 解决方案 > Android Horizo​​ntal Recyclerview 在滚动时显示多项选择

问题描述

我需要选择第一个项目作为默认选择并在点击时选择一个项目。但是当我滚动并看到我可以看到它在每 8 个项目之后被选中。它甚至包括多个项目的左边距,我只包括水平回收器视图中的第一个项目。

companion object {
        private var lastCheckedtab: ConstraintLayout? = null
    }
fun bind(
            context: Context?,
            name: String,
            position: Int
    ) {
        if (position == 0) {
            cardView?.isSelected = true
            cardView?.isClickable = false
            lastCheckedtab = cardView
            val p = cardView?.layoutParams as ViewGroup.MarginLayoutParams?
            p?.leftMargin = 52
        }
        itemView.setOnClickListener{
            val checkedTab = it as ConstraintLayout
            checkedTab.isSelected = true
            checkedTab.isClickable = false
            if (lastCheckedtab != null && lastCheckedtab != checkedTab) {
                lastCheckedtab?.isSelected = false
                lastCheckedtab?.isClickable = true
                context?.let { it1 ->
                    checkedTab.findViewById<TextView>(R.id.iv_tab_name).setTextColor(
                        ContextCompat.getColor(
                            it1,
                            R.color.black
                        )
                    )
                    lastCheckedtab?.findViewById<TextView>(R.id.iv_tab_name)?.setTextColor(
                        ContextCompat.getColor(
                            it1,
                            R.color.setting_text
                        )
                    )
                }
            }
            lastCheckedtab = checkedTab
        }
}        


 override fun onBindViewHolder(holder: MyHolder, position: Int) {
        holder.bind(context, tabs.get(position), position)
    }

标签: androidandroid-recyclerviewhorizontalscrollviewhorizontal-recyclerview

解决方案


那是因为您选择了第一个 ViewHolder,但从未取消选择它。

RecyclerView(顾名思义)回收 ViewHolders 而不是总是制造新的。

如果您只想选择第一个项目,那么您应该进行某种状态保存,以了解选择了哪些项目,并让该状态从第一个项目被选中开始。

然后在绑定 ViewHolder 时,检查位置是否被选中


推荐阅读