【问题标题】:How to work with checkboxes using recyclerview kotlin android如何使用 recyclerview kotlin android 处理复选框
【发布时间】: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


    【解决方案1】:

    您不应该在CheckBox 上使用setOnClickListener ,而是需要使用具有isChecked 回调参数的setOnCheckedChangeListener

    另外,不要在适配器中以编程方式设置 CheckBox 值,因为这应该由用户触发

    所以替换:

    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)
    }
    

    与:

    checkbox.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
        checkBoxStateArray.put(bindingAdapterPosition, isChecked)
    })
    

    【讨论】:

    • 你好。我从评论中读到使用 onCheckedChangeListner 不安全。 stackoverflow.com/a/41843879/15985008我已经替换了,但我的问题仍然存在:在我的片段中获取选定的项目
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 2023-04-11
    • 2016-03-31
    • 1970-01-01
    相关资源
    最近更新 更多