How to select all items which listed in recyclerview?

前端 未结 4 1175
后悔当初
后悔当初 2021-01-13 03:39

I have list of items inside of recyclerview, and they are multiple selectable.

I want to have select button to select all, and if selected deselect all. I didn\'t se

4条回答
  •  生来不讨喜
    2021-01-13 04:34

    There is no need to maintain another list with selected items. You need to create a method to set a flag and in the onBindViewHolder method just check for that flag. Something like this:

    class MyAdapter(val context: Context): RecyclerView.Adapter() {
    
        val mItems = mutableListOf()
        private var selectAllItems: Boolean = false
    
        fun updateList(list: List) {
            mItems.addAll(list)
            notifyDataSetChanged()
        }
    
        fun selectAllItems(selectAll: Boolean){
            selectAllItems = selectAll
            notifyDataSetChanged()
        }
    
        override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
            val pos = viewHolder.adapterPosition
            viewHolder.checkbox.isSelected = selectAllItems
        }
    
        class ViewHolder(val view: View): RecyclerView.ViewHolder(view) {
            val checkbox: Checkbox = view.myCheckBox
        }
    }
    

提交回复
热议问题