samedi 22 mai 2021

Items get re-added in checkbox while scrolling in recycler view android

I have a list of items in a recyclerview containing checkboxes, I am trying to get selected items in a checkbox from my adapter to my fragment.

Problem

The item gets reAdded everytime I scroll to the position of the item.

E.g

When I check an Item, it gets added to my list of selected items - Fine. but when I scroll down and scroll up, the item gets added again. Same thing happens over and over again while scrolling.

Adapter

var checkedSongs = ArrayList<Songs>()
var checkBoxStateArray = SparseBooleanArray()
inner class SelectSongsViewHolder(val binding: RcvLytSelectSongsBinding) : 
RecyclerView.ViewHolder(
    binding.root)
 {
   init {
     binding.checkbox.setOnCheckedChangeListener { buttonView, isChecked ->
     if (isChecked){
        val song = songs[absoluteAdapterPosition]
        checkedSongs.add(song)
       }
       else{
       val song = songs[absoluteAdapterPosition]
       checkedSongs.remove(song)
            }
       checkBoxStateArray.put(bindingAdapterPosition, isChecked)
      }
    }
}

.......
//In onBindViewHolder
binding.checkbox.isChecked = checkBoxStateArray.get(position, false)

//Function to get all checked songs
fun getSelectedSongs(): ArrayList<Songs> {
    return checkedSongs
}

Fragment

binding.txtDone.setOnClickListener {
 val selectedRows = selectSongsAdapter.getSelectedSongs()
 Toast.makeText(requireContext(), selectedRows.toString(), Toast.LENGTH_LONG).show()
}

So lets say I have 5 items in the list

1. 2. 3. 4. 5.

When I check item 1, and click done...Toast message = "[Item(item1)]"

When I scroll down and scroll up.....Toast message = "[Item(item1), Item(item1)]"

...It goes on and on like that.




Aucun commentaire:

Enregistrer un commentaire