Android Jetpack Paging3更新项目

时间:2020-07-28 13:00:07

标签: android android-jetpack android-paging

我正在使用分页3显示数据。当我要更新一些项目时,如何获得这些项目的位置?使用“ notifyItemChanged”。(我知道这些项目的ID,但是没有用于获取适配器数据的api)

1 个答案:

答案 0 :(得分:0)

您可以设置点击侦听器,点击操作后您可以更改项目和更新视图

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

在您的活动中设置点击监听器功能

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

然后更改您的商品并更新视图

private fun recyclerViewClickListener(item : CountryModel?, pos : Int, view : View) {
    item.countryName = "new name"
    adapter.notifyItemChanged(pos, item)
}