Double instantiation of fragments

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).

Sorry for the delay in responding!

Either:

  • Remove the one from the layout (and use a FragmentContainerView for the destination of your replace() 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