When I add an item into one recyclerview it gets two

49 Views Asked by At

I think it's reference problem.

RecyclerViews seem they share items with the same reference.

I created two recyclerviews, And I make a list, and I send the list through a method to create another recyclerview.

For instance,

val myAdapter = MyAdapter()
val myList = ArrayList<String>()

val yourAdapter = MyAdapter()
val yourList: ArrayList<String>? = null

private fun init(){
    initAction()
    list.add("lion")
    list.add("cat")
    list.add("dog")
    myAdapter.setList(list)
    rcvMy.adapter = myAdapter
    
    initOtherRecyclerView(list)
}

private fun initOtherRecyclerView(mList: ArrayList<String>){
    yourList = mList
    yourAdapter.setList(yourList)
    rcvYour.adapter = yourAdapter
}

private fun initAction(){
    btnAdd.setOnClickListener{
        myAdapter.items.add("Hello")
        myAdapter.notifyDataSetChanged()
    }
}

whenever I click the btnAdd, it adds two items into rcvMy.

How can I cut the referencing?

1

There are 1 best solutions below

3
On

Both Adapter are holding same List you can use two separate Lists . And whenever you need a data from list you get it view the Adapter. Below is an example with the example in question .

private fun initOtherRecyclerView(mList: ArrayList<String>){
    yourList.addAll(mList);
    yourAdapter.setList(yourList)
    rcvYour.adapter = yourAdapter
}