Android Fragment Lifecycles

Android Fragment Lifecycles

Like activities fragments also have a lifecycle, the major difference is the fragment’s lifecycle is dependent on the activity’s lifecycle it’s attached to.

onAttach is when the fragment adds its self to the activity

public void onAttach(Activity activity) {
  super.onAttach(activity);
}

onCreate is where data is stored, if it’s the first time then the savedInstanceState is null

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
}

onCreateView is where you connect the fragment xml file to the fragment class

public View onCreateView(Layout Inflater inflater, ViewGroup container, Bundle savedInstanceState) {
  return inflater.inflate(R.layout.fragXML, container, false);
}

onActivityCreated is when you’re waiting for the activity to be completely created, so you can access UI elements in it.

public void onActivityCreated(Bundle savedInstanceState) {
  super.onActivityCreated(savedInstanceState);
}

onStart

public void onStart() {
  super.onStart();
}

onResume

public void onResume() {
  super.onResume();
}

onPause is when the user can no longer interact with it

public void onPause() {
  super.onPause();
}

onSaveInstanceState is when the fragment information is saved before it stops

public void onSavedInstanceState(Bundle outState) {
  super.onSavedInstanceState(outState);
}

onStop is when it’s no longer visible to the user

public void onStop(){
  super.onStop();
}

onDestroyView is where the fragment xml is removed from the hierarchy

public void onDestroyView() {
  super.onDestroyView();
}

onDestroy is when all resources are released

public void onDestroy() {
  super.onDestroy();
}

onDetach is when the fragment is leaving the activity

public void onDetach() {
  super.onDetach();
}

Author: Pawan Kumar

Leave a Reply

Close Menu
%d bloggers like this:
Skip to toolbar