【发布时间】:2022-08-03 07:36:27
【问题描述】:
在 Google 提供的 ViewBinding 示例中,我们需要将 Fragment 的 viewBinding 设置为 null,而 Activity 则不需要。 https://developer.android.com/topic/libraries/view-binding
原因对我来说很明显,因为 Activity 将与它的 View 一起被销毁,但对于 Fragment 不会(Fragment 比它的 View 寿命更长,即当 Fragment 被替换时)。
但是,对于 RecyclerView,如果我们在 ViewHolder 中有 ViewBinding,就像下面的示例(取自 https://stackoverflow.com/a/60427658/3286489),其中 PaymentHolder 存储了一个 ViewBinding(即 itemBinding)。我们需要将其设置为空吗?
class PaymentAdapter(private val paymentList: List<PaymentBean>) : RecyclerView.Adapter<PaymentAdapter.PaymentHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PaymentHolder {
val itemBinding = RowPaymentBinding
.inflate(LayoutInflater.from(parent.context), parent, false)
return PaymentHolder(itemBinding)
}
override fun onBindViewHolder(holder: PaymentHolder, position: Int) {
val paymentBean: PaymentBean = paymentList[position]
holder.bind(paymentBean)
}
override fun getItemCount(): Int = paymentList.size
class PaymentHolder(private val itemBinding: RowPaymentBinding) : RecyclerView.ViewHolder(itemBinding.root) {
fun bind(paymentBean: PaymentBean) {
itemBinding.tvPaymentInvoiceNumber.text = paymentBean.invoiceNumber
itemBinding.tvPaymentAmount.text = paymentBean.totalAmount
}
}
}
我的猜测是 ViewHolder 中的 viewBinding 不需要设置为 null(或释放),因为 ViewHolder 中的 viewBinding 不会超过 ViewHolder。我假设如果 ViewHolder 与 RecyclerView 分离,并且没有被使用,它将被适配器删除,而不需要我们手动释放它拥有的 ViewBinding。
但是在这里检查以防我的理解不正确。
-
@Abdo21,stackoverflow.com/questions/66119231/ 在 Fragment 而不是 ViewHolder 上。
标签: android android-recyclerview android-viewholder android-viewbinding