0

enter image description herehere I change the background of the selected item position and set that item to the first position init

    override fun onBindViewHolder(holder: FeelingsViewHolder, position: Int) {
        val item = dataset[position]
        holder.title.text = context.resources.getString(item.stringResourceId)
        holder.emoji.setImageResource(item.imageResourceId)

        holder.emoji.setOnClickListener {
            selectedItemPos = position

            notifyItemMoved(position, 0)
        }

        if (selectedItemPos == position)         

holder.itemView.setBackgroundColor(Color.parseColor("#200f726b"))
        else
          holder.itemView.setBackgroundColor(Color.parseColor("#ffffff"))
    override fun getItemCount() = dataset.size
}

I tried different ways but I failed

1 Answers1

0

Update:

According to your updated question, you must write something like this:

if (position == 0)
holder.itemView.setBackgroundColor(Color.parseColor("#200f726b"))

Let me know if it didn't work

Original answer:

First, you'd better use notifyItemMoved(position,0) instead of notifyDataSetChanged() because it has less performance overhead. You can read about the reason here:

What's better? notifyDataSetChanged or notifyItemChanged in loop?

if "selectedItemPos" is out of onBind method, the item that has recently been in the first position should be colorful

Hamed Goharshad
  • 631
  • 4
  • 12