dawzaw
dawzaw

Reputation: 429

How to change view of specific item in RecyclerView

Assuming that I have adapter with list of items and view for each item contains textview. How to access this item's textview and for instance change it's color. I can do this by adding a click listener to each item and doing that change of text color when item is clicked. But is there a way to achieve this in other way ?

In my ViewHolder I got:

val info: TextView = view.find(R.id.info_item)

And a method:

fun bindItems(listItem: List<String>) {

                info.text = "Name: ${listItem[0]}"}

PS. I know how to change color of text view :)

Upvotes: 1

Views: 1861

Answers (3)

Kaloglu
Kaloglu

Reputation: 1761

May be you can try following;

  • create a class that was extended RecyclerView.ViewHolder at the same time implemented View.OnClickListener. (e.g MyViewHolder)

  • override constructor if you think it is necessary

  • override onClick function for click handling.

  • call change View method from onClick function.

  • return an instance for MyViewHolder from overrided onCreateView at adapter class.

  • bind new ViewHolder.

Ps: don't forget change type parameter for adapter. (RecyclerView.Adapter)

Upvotes: 0

chandani c patel
chandani c patel

Reputation: 309

use below code , i have tried it and it is working :

private var row_index: Int = -1

itemView.txtContactAddress.setOnClickListener({
                row_index = position;
                notifyDataSetChanged()
            })

if (row_index == position) {
                    itemView.txtContactAddress.setTextColor(Color.parseColor("#ffffff"));
                } else {
                    itemView.txtContactAddress.setTextColor(Color.parseColor("#000000"));
            }

Upvotes: 1

kalabalik
kalabalik

Reputation: 3832

In onBindViewHolder you could do something like this:

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    holder.itemView.setBackgroundColor(if(position%2==0) 0xffff0000.toInt() else 0xff00ff00.toInt())

Upvotes: 2

Related Questions