Double instantiation of fragments
from the CommonsWare Community archivesAt January 5, 2021, 5:37pm, Jan asked:
The setContentView called in my activity automatically instantiates my fragment that is in the activity layout.
setContentView(R.layout.activity_review)
But because the fragment needs an argument passed in that was also passed in the activity intent, I have to instantiate it again with these lines:
val productReviewFragment =
ProductReviewFragment.newInstance(isCurrentProduct)
supportFragmentManager
.beginTransaction()
.replace(R.id.productReviewFragment, productReviewFragment)
.commit()
Everything works. I was just curious – is there a way to avoid the double instantiation (which also calls things like onCreate again).
At January 6, 2021, 1:30pm, mmurphy replied:
Sorry for the delay in responding!
Either:
-
Remove the one from the layout (and use a
FragmentContainerView
for the destination of yourreplace()
operation), or -
Do something else to provide the data to the original fragment in the layout (e.g., call a setter which puts the value in the arguments bundle) and remove the transaction