Android RecyclerView 中的数据绑定不起作用 (Kotlin)

DataBinding in Anroid RecyclerView doesn't work (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

您应该在 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)