Open menu with table of contents Android Fragments
Logo of Stuttgart Media University for light theme Logo of Stuttgart Media University for dark theme
Android Development

Android Fragments

Stuttgart Media University

1 Agenda

  • Fragment Implementation
  • Fragment Lifecycle
  • Changing Fragments in Code

2 Fragment Basics

  • Component introduced in Android 3.0 (API level 11)
  • Multiple Fragments can be combined in one Activity
  • Each Fragment defines a part of the UI in an Activity and must be embedded in an Activity
  • The lifecycle of a Fragment is directly dependent on the Activity's lifecycle
  • But: Fragments can be independently manipulated (e.g. added or removed)
  • The Layout is defined in a layout.xml, the implementation in a class derived from the class Fragment

2.1 Fragment View Layout

  • Two Fragments can be contained in one Activity (left) or in separate Activities (right)


2.2 Fragment View Layout

  • Example Activity Layout with two Fragments
<LinearLayout xmlns:android=""
    android:orientation="horizontal" >
        android:layout_height="match_parent" />
        android:layout_height="match_parent" />

2.3 Fragment Implementation

  • Create a subclass of Fragment
public class ExampleDetailFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.detail_fragment,container, false);
  • And implement onCreateView() returning the View that will be embedded in the surrounding Activity
  • LayoutInflater loads XML based layouts and creates View hierarchy

2.4 Fragment Implementation

√úBERARBEITEN !!!! -> List ersetzen mit Fragment

  • Create a subclass of one of Fragments subclasses, e.g. ListFragment
public class ExampleListFragment extends ListFragment {
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        List<String> songs = Arrays.asList("Blur","Metallica","Bosse");
        ArrayAdapter<String> bandArray = new ArrayAdapter<String>
            (getActivity(), android.R.layout.simple_list_item_1,songs);

2.5 Fragment Lifecycle

Fragments exist in three states when started:

  • Resumed: Fragment is visible and running
  • Paused: Another Activity is in the foreground and has focus but the Fragment is still visible
  • Stopped: Fragment is not visible but still alive. Either Activity has been stopped or Fragment removed

The lifecycle of the Activity directly affects the lifecycle of the Fragment


3 Fragment Lifecycle

Fragment specific lifecycle callbacks are:

  • onAttach(): called when is added to Activity
  • onCreateView(): creates the view hierarchy of the Fragment
  • onActivityCreated(): called when Activity's onCreate() method returned
  • onDestroyView(): called when view hierarchy of Fragment is removed
  • onDetach(): called when Fragment is disassociated with Activity


4 FragmentManager

  • Instead of defining a fragment for an activity in the layout file, it can be added during runtime
  • The FragmentManager class is used to create a FragmentTransaction
    • Provides APIs to add, remove and replace fragments
    • Call commit() when ready to make changes
  • Fragments must have a container view in the layout

4.1 Loading Fragments dynamically

ArticleFragment newFragment = new ArticleFragment();
FragmentTransaction transaction = getFragmentManager().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(, newFragment);

// Commit the transaction

5 Jetpack Navigation

Modern applications prefer the usage of Jetpack Navigation over manual fragment transactions.

6 Android Assignment 4

7 Summary

  • Fragments are a good way to create flexible user interfaces
  • They encapsulate a UI-Controller for an logical part of the UI. This simplifies component oriented UI programming on Android
  • They can be statically added to layout files for different device types and also be used dynamically to change the UI corresponding to changes of the devices screen

8 Recap Questions

  • When would you use a Fragment and when only an Activity?
  • When dynamically replacing a Fragment, what is required in the layout? Try to replace a Fragment dynamically.
  • Why do you have to call commit, when dynamically changing fragments?
  • When accessing a view component that is added in one Fragment from another Fragment, what do you have to consider concerning the lifecycle?
  • Which methods are "safe" to access view components from?