簡體   English   中英

Android - OnResume 在 Recyclerview 中的 onBindViewHolder 中

[英]Android - OnResume inside onBindViewHolder in Recyclerview

我有一個 RecyclerView 列出文章,在onBindViewHolder每篇文章/項目中,我正在加載另一個 RecyclerView 以獲取評論,當用戶返回活動時,我需要更新它們。

有沒有一種方法來檢測活動OnResumeonBindViewHolder父RecyclerView的?

我假設您有一些文章數據類,其中包含其詳細信息和評論。 您將此列表傳遞給第一個回收器,它在 onBind 中用數據填充注釋回收器。 如果您必須更新評論,只需將帶有更新評論的文章列表傳遞給文章的適配器。 它會觸發onBindViewHolder在里面你會有新的評論。 在代碼中它會是這樣的:

data class Article (
    val name: String
    ... other details
    val comments: List<Comment>
)

文章適配器的 onBindViewHolder:

override fun onBindViewHolder(holder: Holder, position: Int) {
    val article = getItem(position)

    // here you should submit list of comments
    commentsAdapter.submitList(article.comments)
}

並在活動中:

override fun onResume() {
    super.onResume()

    //get new comments here and set it for new articles
    val newArticles = oldArticles.map { article -> it.copy(comments = newComments)}
    articlesAdapter.submitList(newArticles)
}

順便說一下,似乎 AdapterDelegates 會更好地解決您的問題。 在此處閱讀更多信息: http : //hannesdorfmann.com/android/adapter-delegates

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM