I have two fragments: Fragment A contains a recyclerview of 5 article items and Fragment B contains the webview of the selected article in Fragment A.
Upon going back from Fragment B to A, my items in the recyclerview in Fragment A doubled. So basically, Fragment A is now showing duplicate items which are not what I want.
I tried to override the onResume
method in Fragment A like this but no luck:
override fun onResume() {
super.onResume()
arrayArticles.clear()
val articlesAdapter = TipsRecyclerAdapter(arrayArticles, this)
binding.tipsRecyclerView.layoutManager = LinearLayoutManager(context)
binding.tipsRecyclerView.adapter = articlesAdapter
}
PS: I am using the navigation component to navigate between fragments.
CodePudding user response:
As commented by @ADM, I moved my adapter setup to onViewCreated()
. I found a simple fix that I just added at onCreateView()
:
if(arrayArticles.size == 0){
arrayArticles.add(article1)
arrayArticles.add(article2)
...
}
...
then on onViewCreated()
:
super.onViewCreated(view, savedInstanceState)
val articlesAdapter = TipsRecyclerAdapter(arrayArticles, this)
binding.tipsRecyclerView.layoutManager = LinearLayoutManager(context)
binding.tipsRecyclerView.adapter = articlesAdapter
Checking the arraylist size is necessary because I think the adding of articles into the arraylist is executed again upon back navigation