将回收者视图中显示的选中复选框的项目保存在列表中 [英] Save items of checked checkboxes displayed in recycler view in a list
问题描述
我设法在带有 checkboxes
的 recycler view
中显示存储在房间数据库中的项目,我想将选中的项目存储在列表中,以存储选中的项目列表中的项目我在复选框上使用 setOnClickListener
,就像适配器中的下面代码一样,但是当我单击以显示列表时应用程序会停止,或者即使列表成功显示有时也会在我单击时停止项目的复选框(有关信息,当我删除侦听器时,列表显示良好,我可以单击 checkboxes
并且一切正常,但问题是当我添加侦听器以存储选中的项目时).
I manage to display the items stored in a room database in a recycler view
with checkboxes
and i want to store the checked items in a list, to store the checked items on a list I use setOnClickListener
on the checkbox like the code below in adapter but the application stop when i click to display the list or even if the list displayed with success sometimes it stops when i click on the checkbox of an item (for information when i remove the listener the list is displayed well and I can click on the checkboxes
and everything works well but the problem is when i add the listener to store the checked items).
class Adapter (val selectedFluxs : MutableList<Flux>) : RecyclerView.Adapter<Adapter.VH>(
) {
class VH(itemView: View) : RecyclerView.ViewHolder(itemView){
lateinit var feed : Flux
}
var allFluxs : List<Flux> = listOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
val v = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.item_layout, parent, false)
val holder = VH( v )
v.check.setOnClickListener( ) {
// it as CheckBox
if( v.check.isChecked ){
selectedFluxs.add ( holder.feed )
}else{
selectedFluxs.remove( holder.feed )
}
}
return holder
}
override fun getItemCount(): Int {
return allFluxs.size
}
fun setFlux( allFlux : List<Flux> ) {
this.allFluxs = allFlux
notifyDataSetChanged()
}
override fun onBindViewHolder(holder: VH, position: Int) {
holder.itemView.apply {
Source.text = allFluxs[position].source
Tag.text = allFluxs[position].tag
Url.text = allFluxs[position].adr
check.isChecked =
holder.feed in selectedFluxs
}
}
}
推荐答案
我发帖一分钟就解决了问题,其实问题是我没有初始化变量:lateinit var feed: Flux
在 onBindViewHolder 方法中使用: holder.feed = allFluxs[position]
.我做到了,并且有效.
I solved the problem a minute after posting the question, in fact the problem is that I did not initialize the variable : lateinit var feed: Flux
of the Holder with : holder.feed = allFluxs[position]
in the onBindViewHolder method . i did that and it works .
这篇关于将回收者视图中显示的选中复选框的项目保存在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!