如何更新适配器数据列表?
Posted
技术标签:
【中文标题】如何更新适配器数据列表?【英文标题】:how can update adapter data list? 【发布时间】:2021-02-22 10:11:30 【问题描述】:我在 recyclerView 适配器中更新我的数据列表时遇到问题,
我正在调用 webservice 来获取 main.activity 中的数据列表,如下所示:
private fun get_company_name()
val request = buildService(ApiInterface::class.java)
val call = request.getCompanyList()
call.enqueue(object : Callback<List<CompanyModel>>
override fun onResponse(call: Call<List<CompanyModel>>, response: Response<List<CompanyModel>>)
if (response.isSuccessful)
indeterminateBar.visibility = View.INVISIBLE
frg_holder.apply
setHasFixedSize(true)
layoutManager = LinearLayoutManager(this@MainActivity)
adapter = DidebanAdapter(response.body()!!)
override fun onFailure(call: Call<List<CompanyModel>>, t: Throwable)
indeterminateBar.visibility = View.INVISIBLE
)
这是我的适配器:
class DidebanAdapter(val didebans: List<CompanyModel>): RecyclerView.Adapter<DidebanViewHolder>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DidebanViewHolder
val view = LayoutInflater.from(parent.context).inflate(R.layout.fragment_dideban, parent, false)
return DidebanViewHolder(view)
override fun getItemCount(): Int
return didebans.size
override fun onBindViewHolder(holder: DidebanViewHolder, position: Int)
holder.itemView.delete_dideban.setOnClickListener(View.OnClickListener view ->
val id : Int = holder.itemView.dideban_id.text.toString().toInt();
val request = ApiClient.buildService(ApiInterface::class.java)
val call = request.deleteCompany(id)
call.enqueue(object : Callback<Boolean>
override fun onResponse(call: Call<Boolean>, response: Response<Boolean>)
notifyItemRemoved(position)
override fun onFailure(call: Call<Boolean>, t: Throwable)
Log.e("msg","false")
)
)
return holder.bind(didebans[position])
class DidebanViewHolder(itemView : View): RecyclerView.ViewHolder(itemView)
private val title:TextView = itemView.findViewById(R.id.dideban_name)
private val dideban_id:TextView = itemView.findViewById(R.id.dideban_id)
fun bind(dideban: CompanyModel)
title.text = dideban.Title
dideban_id.text = dideban.Id.toString()
在 onBindViewHolder 函数中,我为单击的删除图像设置了操作,它调用另一个 Web 服务并从数据库中删除项目,它工作正常,但我希望我的适配器在项目被删除时更新。 我使用 notifyItemRemoved(position),但它无法按需更新我的列表。
【问题讨论】:
【参考方案1】:在notifyItemRemoved(position)
之前,您应该手动从列表中删除元素(适配器不会为您这样做)didebans.remove(position)
【讨论】:
哦,真不敢相信忘了这行,非常感谢以上是关于如何更新适配器数据列表?的主要内容,如果未能解决你的问题,请参考以下文章