我试图改变回收视图项目的背景颜色,但这不起作用。我不知道为什么。这可能是约束布局的问题吗?我尝试了几个教程和类似的问题,但此时我真的很困惑。
<<p>适配器/strong>class ExampleAdapter(private val exampleList: List<ExampleItem>):
RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder>()
{
var onItemClick: ((ExampleItem, Int) -> Unit)? = null
var onItemLongClick: ((ExampleItem) -> Boolean)? = null
var selected_item: Int = RecyclerView.NO_POSITION
//var examples: List<ExampleItem> = emptyList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_recy, parent, false)
return ExampleViewHolder(itemView)
}
override fun onBindViewHolder(holder: ExampleViewHolder, position: Int){
val currentItem = exampleList[position]
holder.tv_ID.text = currentItem.id.toString()
holder.tv_NAME.text = currentItem.name
if (position == selected_item){
holder.itemView.setBackgroundColor(Color.parseColor("#7ADE4A"))
} else {
holder.itemView.setBackgroundColor(Color.parseColor("#E0CC62"))
}
}
override fun getItemCount(): Int {
return exampleList.size
}
inner class ExampleViewHolder(itemView:View): RecyclerView.ViewHolder(itemView) {
val tv_ID: TextView = itemView.tv_ID
val tv_NAME: TextView = itemView.tv_NAME
init {
itemView.setOnClickListener{
onItemClick?.invoke(exampleList[absoluteAdapterPosition], absoluteAdapterPosition)
itemView.setSelected(true)
notifyItemChanged(selected_item)
selected_item = absoluteAdapterPosition
notifyItemChanged(selected_item)
}
}
itemView.setOnLongClickListener {
onItemLongClick?.invoke(exampleList[absoluteAdapterPosition])
true
}
}
}
}
我在layout xml中使用ConstraintLayout和ScrollView。RecyclerView在TableLayout中。这应该是个问题吗?
Change-
var selected_item: Int = RecyclerView.NO_POSITION
这个——
var selected_item: Int = 0
RecyclerView。NO_POSITION此值自动更新,您的selected_item始终等于当前项目的位置。
在上面的代码中,您正在根据条件
设置颜色position == selected_item
但是selected_item正在viewholder click listener中被更新。意味着只有在我们点击item之后,selected_item才会被更新。在此之前,它将是RecyclerView。NO_POSITION当onBindViewHolder被调用时,它将是NO_POSITION。
所以,你可以在onClickListener中处理背景色在ViewHolder中呈现