首页 > 解决方案 > Anroid RecyclerView 中的数据绑定不起作用(Kotlin)

问题描述

这是我的 OnBindViewHolder 函数代码:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val country = countries[position]
    var countryInfoCardBinding = DataBindingUtil.setContentView<CountryInfoCardBinding>(context as Activity, R.layout.country_info_card)
    countryInfoCardBinding.country = country
}

这是我的 XML 文件:

https://pastebin.com/PySQFLmv

标签: androidkotlinandroid-databindingandroid-jetpack

解决方案


您应该在 中膨胀数据绑定对象onCreateViewHolder,而不是onBindViewHolder. 现在您正在膨胀一个与您的视图无关的对象,这就是为什么(我假设)什么都没有出现

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val country = countries[position]
    holder.binding.country = country
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val binding = CountryInfoCardBinding.inflate(
        LayoutInflater.from(parent.context),
        parent,
        false
    )

    return ViewHolder(binding)
}

inner class ViewHolder(val binding: CountryInfoCardBinding) : RecyclerView.Viewholder(binding.root)

推荐阅读