0

I am using paging3 to display data. When I want to update a few items, how do I get the position of these items? use "notifyItemChanged".(I know the id of these items, but there is no api to get the adapter data)

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

1 Answers1

0

You can set click listener and after click action you can change item and update view

    class Adapter(val countryList: MutableList<CountryModel>,
    clickFunc : ((CountryModel?, Int, View) -> Unit)? = null) : RecyclerView.Adapter<Adapter.ModelViewHolder>() {
    
        class ModelViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val countryName: TextView = view.findViewById(R.id.countryName)
            val capitalName: TextView = view.findViewById(R.id.capitalName)
            val flagImage: ImageView = view.findViewById(R.id.flagImage)
            
            fun bindItems(item: CountryModel) {
                countryName.setText(item.countryName)
                capitalName.setText(item.capitalName)
                flagImage.setImageResource(item.flagImage)

                view.setOnClickListener {
                   clickFunc?.invoke(item, adapterPosition, view)
                }
            }
        }
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ModelViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_card, parent, false)
            return ModelViewHolder(view)
        }
    
        override fun getItemCount(): Int {
            return countryList.size
        }
    
        override fun onBindViewHolder(holder: ModelViewHolder, position: Int) {
            holder.bindItems(countryList.get(position))
        }
    }

In your activity set a click listener function

recyclerView.adapter = Adapter(getModels()) { item, pos, view -> 
      recyclerViewClickListener(item, pos, view) 
}

Then change your item and update view

private fun recyclerViewClickListener(item : CountryModel?, pos : Int, view : View) {
    item.countryName = "new name"
    adapter.notifyItemChanged(pos, item)
}
ysfcyln
  • 2,857
  • 6
  • 34
  • 61