How to recognize recycler if both use the same adapter?

Viewed 22

I got recyclerOne and recyclerTwo. Both of them use the same adapter and same item layout. I need to set recyclerOne item text color to black and recyclerTwo item text color to blue. How to recognize inside adapter view holder which recycler items it handles to set the correct color in onBind() method?

1 Answers

You can simply take a parameter in the adapter constructor like this:

class MyAdapter(private var mList: ArrayList<YourList>, private val check: Int) : RecyclerView.Adapter<RecyclerView.ViewHolder>()

Then in the onBindView, you can check which RecyclerView set the adapter like this:

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    if (check == 1) // set item color to black
    else if (check == 2) // set item color to blue
}

And lastly, while setting the adapter, you can pass the check parameter like this:

For recyclerOne:

val adapter = MyAdapter(myList, 1)
binding.recyclerOne.adapter = adapter

For recyclerTwo:

val adapter = MyAdapter(myList, 2)
binding.recyclerTwo.adapter = adapter
Related