Performing Fragment Transactions
by, 02-11-2012 at 12:25 PM (934 Views)
You can add, remove, replace or perform actions with fragments in your activity in response to user interaction. A transaction is a set of changes you perform to an activity and these can be performed using APIs in FragmentTransaction. These transaction can be saved on back stack and allow the user to navigate these changes.
To get an instance from FragmentManager, following code is used.
Add all the changes you want to perform using add(), remove() and replace() methods and make a transaction. This transaction will be applied to an activity and finally call commit().Java Code: This is the code to create a fragmentFragmentManager fragmentManager = getFragmentManager() FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Call addToBackStack() method to add the transaction to stack before you call the commit() method. Activity is managing this stack and user can return to back state by pressing BACK key.
Following code explains this scenario in which you can replace a fragment.
Java Code: This is the code to explain the add methodExampleFragment fragment = new ExampleFragment(); fragmentTransaction.add(R.id.fragment_container, fragment); fragmentTransaction.commit();