Sapan Diwakar

Software developer

Follow me on Twitter Check out my code on GitHub View some of my designs on Dribbble Take a look at my Linked In profile

Replacing one fragment with another in Android dynamically

I needed to replace fragment in an Android application when I was using Tab bar and I needed to change fragment when tab bar is changed. At first, I defined the fragment statically in layout file and when I tried to change it dynamically I received an error. Then I found out that it is only possible to change those fragments defined dynamically via a FragmentTransaction.

Here is a quick example from documentation:

// Create fragment and give it an argument specifying the article it should show
ArticleFragment newFragment = new ArticleFragment();  
Bundle args = new Bundle();  
args.putInt(ArticleFragment.ARG_POSITION, position);  
newFragment.setArguments(args);

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);  
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();  

Note: When you remove or replace a fragment and add the transaction to the back stack, the fragment that is removed is stopped (not destroyed). If the user navigates back to restore the fragment, it restarts. If you do not add the transaction to the back stack, then the fragment is destroyed when removed or replaced. To allow the user to navigate backward through the fragment transactions, you must call addToBackStack() before you commit the FragmentTransaction.