【发布时间】:2021-05-20 19:43:40
【问题描述】:
我正在尝试:
在我的片段中获取选中的复选框项
我的尝试
所以,据我所知,在 recyclerview 中滚动时有两种保存复选框状态的方法
- 使用 SparseBooleanArray ()
- 使用模型保存状态
我选择了选项 1。
模型 - Songs.kt
data class Songs(
val songId: Int? = null,
)
适配器 - 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)
}
}
片段 - 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())
问题
如何将选定的项目从适配器获取到片段。 我的代码返回一个空列表。
我想从适配器获取任何选中/选中的项目到我的片段(观察变化)
【问题讨论】:
标签: android kotlin android-recyclerview android-adapter