Replacing a fragment with another fragment inside activity group Replacing a fragment with another fragment inside activity group java java

Replacing a fragment with another fragment inside activity group


Fragments that are hard coded in XML, cannot be replaced. If you need to replace a fragment with another, you should have added them dynamically, first of all.

Note: R.id.fragment_container is a layout or container of your choice in the activity you are bringing the fragment to.

// Create new fragment and transactionFragment newFragment = new ExampleFragment();FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();// Replace whatever is in the fragment_container view with this fragment,// and add the transaction to the back stack if neededtransaction.replace(R.id.fragment_container, newFragment);transaction.addToBackStack(null);// Commit the transactiontransaction.commit();


Please see this Question

You can only replace a "dynamically added fragment".

So, if you want to add a dynamic fragment, see this example.


I've made a gist with THE perfect method to manage fragment replacement and lifecycle.

It only replace the current fragment by a new one, if it's not the same and if it's not in backstack (in this case it will pop it).

It contain several option as if you want the fragment to be saved in backstack.

=> See Gist here

Using this and a single Activity, you may want to add this to your activity:

@Overridepublic void onBackPressed() {    int fragments = getSupportFragmentManager().getBackStackEntryCount();    if (fragments == 1) {            finish();            return;    }    super.onBackPressed();}