【发布时间】:2021-01-23 23:19:27
【问题描述】:
我正在使用 Kotlin 构建一个 Android 应用程序,并决定替换对 findViewById 的调用并使用绑定。这一切都很好,但特别是,当我为 RecyclerView 更改适配器时,它会破坏项目布局。
带有findViewById的原始代码:
class WeightListAdapter(val weights: List<WeightWithPictures>, val onWeightItemClickListener: OnWeightItemClickListener) : RecyclerView.Adapter<WeightListAdapter.WeightHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WeightListAdapter.WeightHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item_weight, parent, false)
return WeightHolder(view)
}
override fun onBindViewHolder(holder: WeightListAdapter.WeightHolder, position: Int) {
val weightWithPictures = weights[position]
holder.bind(weightWithPictures)
}
override fun getItemCount() = weights.size
inner class WeightHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
private lateinit var weight: Weight
private val weightValueView: TextView = this.itemView.findViewById(R.id.weightValue)
private val weightDateView: TextView = this.itemView.findViewById(R.id.weightDate)
private val weightImageView: ImageView = this.itemView.findViewById(R.id.weightImage) as ImageView
这是布局:
但是每当我使用绑定时:
class WeightListAdapter(val weights: List<WeightWithPictures>, val onWeightItemClickListener: OnWeightItemClickListener) : RecyclerView.Adapter<WeightListAdapter.WeightHolder>() {
private var _binding: ListItemWeightBinding? = null
private val binding get() = _binding!!
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WeightListAdapter.WeightHolder {
_binding = ListItemWeightBinding.inflate(LayoutInflater.from(parent.context))
val view = binding.root
return WeightHolder(view)
}
override fun onBindViewHolder(holder: WeightListAdapter.WeightHolder, position: Int) {
val weightWithPictures = weights[position]
holder.bind(weightWithPictures)
}
override fun getItemCount() = weights.size
inner class WeightHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
private lateinit var weight: Weight
private val weightValueView: TextView = binding.weightValue
private val weightDateView: TextView = binding.weightDate
private val weightImageView: ImageView = binding.weightImage
布局中断:
关于我在这里做错了什么有什么想法吗?是bug吗?
P.S - 现在,我只是为项目视图添加注释以忽略绑定为 documented here,但我真的很想了解问题所在。
【问题讨论】:
-
我的回答完全错误(因为我没有正确阅读)但我至少可以给你一个提示!您可以使用
lateinit var binding: ListItemWeightBinding来避免您对binding变量对所做的事情,并使其保持非空而不需要对其进行初始化。您只需要在读取之前分配一个值(就像您在这里所做的那样) -
感谢您的提示,我会尝试,清理代码会很棒。
标签: android kotlin android-recyclerview android-binder