Android Horizontal 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)
}

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

RecyclerView(顾名思义)回收viewholder,而不是总是创建新的。

如果你想只选择第一个项目,那么你应该有某种状态保存,知道哪些项目被选中,并让状态从第一个项目开始。

当你绑定ViewHolder时,检查位置是否被选中

最新更新