[英]Replacing Kotlin synthetic imports in RecyclerViewAdapter
由於從長遠來看合成導入將被棄用,我開始用視圖綁定替換它們。 到目前為止效果很好,但是在 recyclerview 適配器中構建視圖時我遇到了困難。
//other stuff [...]
private lateinit var binding: FinapiBankItemBinding
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): FinApiBankItemViewHolder {
binding = FinapiBankItemBinding.inflate(LayoutInflater.from(parent.context))
return FinApiBankItemViewHolder(binding.root as ConstraintLayout)
}
//more stuff [...]
override fun onBindViewHolder(
holder: FinApiBankItemViewHolder,
position: Int
) {
if (data != null && data.size > position) {
val currentItem = data[position]
buildView(holder.paymentAccountBaseView, currentItem)
}
}
// endregion
// region methods
private fun buildView(view: View, item: FinApiBank) {
//binding.bankNameTextView.text = item.name
//binding.bicTextView.text = item.bic
view.findViewById<TextView>(R.id.bankName_TextView).text = item.name
view.findViewById<TextView>(R.id.bic_TextView).text = item.bic
binding.root.setOnClickListener {
parentViewModel.getAndNavWebform(item.externalId!!)
}
}
在buildView方法中,我注釋掉的兩行沒有按預期工作。 視圖構建正確,但不知何故存在令人耳目一新的問題,並且最終呈現舊數據(即使步入它並看到正確的值寫入字段中)。
當使用傳統的findViewById甚至 viewBinding(這不是一個選項)時,一切都按預期工作。
此 recyclerview 中使用的數據經常交換,因為它顯示了根據用戶輸入更新的搜索結果。
您也可以使用綁定搜索此 RecyclerView但是我稍微編輯了您的代碼。
嘗試這樣的事情:
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): FinApiBankItemViewHolder {
binding = FinapiBankItemBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return FinApiBankItemViewHolder(binding)
}
//more stuff [...]
override fun onBindViewHolder(
holder: FinApiBankItemViewHolder,
position: Int
) {
if (data != null && data.size > position) {
val currentItem = data[position]
holder.buildView(holder.binding, currentItem)
}
}
// endregion
// region methods
inner class FinApiBankItemViewHolder(val binding: FinapiBankItemBinding): RecyclerView.ViewHolder(binding.root) {
fun buildView(view: FinapiBankItemBinding, item: FinApiBank) {
binding.bankNameTextView.text = item.name
binding.bicTextView.text = item.bic
binding.root.setOnClickListener {
parentViewModel.getAndNavWebform(item.externalId!!)
}
}
}
您似乎對每一行數據使用單個綁定,您的綁定應該在ViewHolder
中,以便可以在onBindViewHolder
中訪問它。
我建議查看使用 RecyclerView 創建動態列表,以獲取有關ViewHolder
用途的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.