LifeCycle

Fragment lifecycle is similar to Activity lifecycle

  • Lifecycle callbacks define how Fragment behaves in each state

    • States

      • Active(or Resumed)

      • Paused

      • Stopped

Activity state

Fragment callbacks triggered

Fragment lifecycle

Created

Fragment is added and its layout is inflated

Started

Fragment is active and visible

Resumed

Fragment is active and ready for user interaction

Paused

Fragment is paused because Activity is paused

Stopped

Fragment is stopped and no longer visible

Destroyed

Fragment is destroyed

@Override onCreate(Bundle savedInstanceState):

  • System calls onCreate() when the Fragment is created

  • Initialize Fragment components and variables (preserved if the Fragment is paused and resumed)

  • Always include super.onCreate(savedInstanceState) in lifecycle callbacks

@Override onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState):

  • Inflate XML layout—required if Fragment has a UI

  • System calls this method to make Fragment visible

  • Must return the root View of Fragment layout or null if the Fragment does not have a UI

More Callbacks

Called when Fragment is first attached to Activity

Called when Activity is paused

Called by Activity to resume a visible Fragment

Called when Activity onCreate() method has returned

Called when View previously created by onCreateView() is detached from Fragment

onActivityCreated(): Called when the Activity onCreate() method has returned

Use onDestroyView() to perform action after Fragment is no longer visible

  • Called afteronStop() and before onDestroy()

  • View that was created in onCreateView() is destroyed

  • A new View is created next time Fragment needs to be displayed

Activity Context

When Fragment is active or resumed:

View listView = getActivity().findViewById(R.id.list);

Get Fragment by calling findFragmentById() on FragmentManager:

ExampleFragment fragment = (ExampleFragment)
     getFragmentManager().findFragmentById(R.id.example_fragment);
// ...
mData = fragment.getSomeData();

Add Fragment to back stack: addToBackStack(null)

  • Host Activity maintains back stack even after Fragment is removed

  • Allows navigation with Back button

fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

Last updated