Android Horizontal Recyclerview 在滚动时显示多个选择 [英] Android Horizontal Recyclerview Shows multiple select on scroll
问题描述
我需要选择第一个项目作为默认选择并在单击时选择一个项目.但是当我滚动查看时,我可以看到它在每 8 个项目之后被选中.它甚至包括多个项目的左边距,我只包括水平回收视图中的第一个项目.
I need to select the first item as default selection and selecting a single item on click. But when I scroll and see I could see it selected after every 8th item.it even included the margin-left for multiple items, which I only included for the first item in horizontal recyclerview.
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,但从未取消选择它.
That is because you selected the first ViewHolder, but never unselected it.
RecyclerView(顾名思义)回收 ViewHolders 而不是总是制作新的.
RecyclerView (as the name suggests) recycles the ViewHolders instead of always making new ones.
如果您只想选择第一个项目,那么您应该进行某种状态保存,以了解选择了哪些项目,并让该状态从第一个被选中的项目开始.
If you want to only select the first item, then you should have some sort of state saving, to know what items are selected, and have that state start with the first item as selected.
然后当你绑定ViewHolder时,检查位置是否被选中
Then when you bind the ViewHolder, check if the position is selected or not
这篇关于Android Horizontal Recyclerview 在滚动时显示多个选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!