I am trying to:
Get selected checked checkbox item in my fragment
What I have Tried
So, as I know there are 2 ways of saving state of checked box while scrolling in recyclerview
- Using SparseBooleanArray ()
- Using your model to save the state
I went for option 1.
Model - Songs.kt
data class Songs(
val songId: Int? = null,
)
Adapter - SelectSongAdapter.kt
//In OnBindViewHolder -
binding.checkbox.isChecked = checkBoxStateArray.get(position,
false)
//function to get all checked songs
fun getSelectedIds(): SparseBooleanArray {
return checkBoxStateArray
}
//In adapter viewHolder
checkbox.setOnClickListener {
if (!checkBoxStateArray.get(bindingAdapterPosition, false)).
{//checkbox checked
checkbox.isChecked = true
//stores checkbox states and position
checkBoxStateArray.put(bindingAdapterPosition, true)
} else {//checkbox unchecked
checkbox.isChecked = false
//stores checkbox states and position.
checkBoxStateArray.put(bindingAdapterPosition, false)
}
}
Fragment - SelectSongFragment.kt
//get selected items - this returns an empty list, even when some
items are checked
val selectedRows = selectSongsAdapter.getSelectedIds()
Log.e("selectedSongs", selectedRows.toString())
QUESTION
How to get the selected items from adapter to fragment. My code is returning an empty list.
I want to get any checked/selected item from the adapter to my fragment (observing changes)