Double instantiation of fragments

from the CommonsWare Community archives

At 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: