View RSS Feed

Android Development

Performing Fragment Transactions

Rate this Entry
by , 02-11-2012 at 12:25 PM (1382 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.


Java Code: This is the code to create a fragment
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
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().

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 method
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

Submit "Performing Fragment Transactions" to Facebook Submit "Performing Fragment Transactions" to Digg Submit "Performing Fragment Transactions" to del.icio.us Submit "Performing Fragment Transactions" to StumbleUpon Submit "Performing Fragment Transactions" to Google

Comments