Modular design to different screen orientations and multiple screen sizes • Multiple fragments can reside in a single activity • Reuse a fragment in multiple activities • Has its own lifecycle
more dynamic and flexible UI designs on large screens • Allow designs without the need to manage complex changes to the view hierarchy • What about previous versions of Android?
or later • APIs work almost exactly the same as their counterparts in the latest Android platform ◦ android.support.v4.app.FragmentActivity ◦ android.support.v4.app.Fragment ◦ android.support.v4.app.FragmentManager ◦ android.support.v4.app.FragmentTransaction
to place the fragment • using the add() method, specifying the fragment to add and the view in which to insert FragmentManager fragmentManager = getFragmentManager() FragmentTransaction fragmentTransaction = fragmentManager. beginTransaction(); ExampleFragment fragment = new ExampleFragment(); fragmentTransaction.add(R.id.fragment_container, fragment); fragmentTransaction.commit();
for the activity without presenting additional UI • it does not receive a call to onCreateView() ExampleFragment fragment = new ExampleFragment(); fragmentTransaction.add(fragment, "FragmentTag"); fragmentTransaction.commit(); • get the fragment from the activity later, you need to use findFragmentByTag()
Create new fragment and transaction Fragment newFragment = new ExampleFragment (); FragmentTransaction transaction = getFragmentManager().beginTransaction (); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack transaction.replace(R.id.fragment_container , newFragment); transaction.addToBackStack (null); // Commit the transaction transaction.commit();
activity automatically re-instantiate existing fragments. // Tell the framework to try to keep this fragment around // during a configuration change. setRetainInstance(true); • Check your Bundle. public void onCreate(Bundle savedInstanceState) { if (savedInstanceState == null){ Do Create the Fragment }else{ Activity was recreated } }