onBindViewHolder。 因此,活动显示空白屏幕。
当我在logcat上看到时,列表大小和itemCount为20,但是从未调用过onBindViewHolder方法。
class NewsAdapter : RecyclerView.Adapter<NewsAdapter.ViewHolder>() {
private val listArticle = mutableListOf<Article>()
fun update(list: List<Article>) {
listArticle.addAll(list)
notifyDataSetChanged()
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): NewsAdapter.ViewHolder {
return ViewHolder(viewGroup)
}
class ViewHolder(
private val parent: ViewGroup,
private val binding: AdapterNewsBinding = DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
R.layout.adapter_news,
parent,
false
)
) : RecyclerView.ViewHolder(binding.root) {
fun bind(article: Article) {
binding.article = article
}
}
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
Log.d("NewsAdapter", "onBindViewHolder")
viewHolder.bind(listArticle[position])
}
override fun getItemCount() = listArticle.size
}
如何通过数据绑定在Recyclerview中调用onBindViewHolder? 这样我就可以在Activity上显示数据了。
答案 0 :(得分:0)
已解决
companion object {
@BindingAdapter("items")
@JvmStatic
fun RecyclerView.bindItems(items: List<Article>?) {
val adapter = adapter as NewsAdapter
if (!items.isNullOrEmpty()) adapter.update(items)
}
}
完成