android - 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(顾名思义)回收 ViewHolders 而不是总是制造新的。
如果您只想选择第一个项目,那么您应该进行某种状态保存,以了解选择了哪些项目,并让该状态从第一个项目被选中开始。
然后在绑定 ViewHolder 时,检查位置是否被选中
推荐阅读
- pandas - 将 Dataframe 推送到 Presto
- sql - “combined_lead_score”列的平均值
- azure - 带有 Azure AD SSO 的 Web 应用:是否可以让外部租户的用户访问他们的电子邮件?
- python - Python根据另一列将值从一行复制到另一行
- sql-server - Docker SQL Server 更改服务器名称本地
- java - Java中HashSet.contains的时间复杂度
- javascript - 如何以角度从http请求返回完全初始化的对象
- aws-lambda - 无法在 Terraform 中使用 AWS SecretManager 添加 Lambda 函数
- java - 是否可以设置 Jackson 以将未命名的包装器对象排除到 API 返回的 JSON 数组中?
- c# - 从 Mat 的特定值创建蒙版(在 EMGU 中)