# 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**        | <ul><li>   <a href="https://developer.android.com/reference/android/app/Fragment.html#onAttach(android.content.Context)"><strong><code>onAttach()</code></strong></a></li><li><a href="https://developer.android.com/reference/android/app/Fragment.html#onCreate(android.os.Bundle)"><strong><code>onCreate()</code></strong></a></li><li><a href="https://developer.android.com/reference/android/app/Fragment.html#onCreateView(android.view.LayoutInflater,%20android.view.ViewGroup,%20android.os.Bundle)"><strong><code>onCreateView()</code></strong></a></li><li><a href="https://developer.android.com/reference/android/app/Fragment.html#onActivityCreated(android.os.Bundle)"><strong><code>onActivityCreated()</code></strong></a></li></ul> | Fragment is added and its layout is inflated      |
| **Started**        | <ul><li><a href="https://developer.android.com/reference/android/app/Fragment.html#onStart()"><strong><code>onStart()</code></strong></a></li></ul>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       | Fragment is active and visible                    |
| **Resumed**        | <ul><li><a href="https://developer.android.com/reference/android/app/Fragment.html#onResume()"><strong><code>onResume()</code></strong></a></li></ul>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     | Fragment is active and ready for user interaction |
| **Paused**         | <ul><li><a href="https://developer.android.com/reference/android/app/Fragment.html#onPause()"><strong><code>onPause()</code></strong></a></li></ul>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       | Fragment is paused because Activity is paused     |
| **Stopped**        | <ul><li><a href="https://developer.android.com/reference/android/app/Fragment.html#onStop()"><strong><code>onStop()</code></strong></a></li></ul>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         | Fragment is stopped and no longer visible         |
| **Destroyed**      | <ul><li><a href="https://developer.android.com/reference/android/app/Fragment.html#onDestroyView()"><strong><code>onDestroyView()</code></strong></a></li><li><a href="https://developer.android.com/reference/android/app/Fragment.html#onDestroy()"><strong><code>onDestroy()</code></strong></a></li><li><a href="https://developer.android.com/reference/android/app/Fragment.html#onDetach()"><strong><code>onDetach()</code></strong></a></li></ul>                                                                                                                                                                                                                                                                                                 | Fragment is destroyed                             |

**@Override** [**`onCreate(Bundle savedInstanceState)`**](https://developer.android.com/reference/android/app/Fragment.html#onCreate\(android.os.Bundle\))**:**&#x20;

* 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)`**](https://developer.android.com/reference/android/app/Fragment.html#onCreateView\(android.view.LayoutInflater,%20android.view.ViewGroup,%20android.os.Bundle\))**:**

* Inflate XML layout—required if Fragment has a UI
* System calls this method to make Fragment visible&#x20;
* Must return the root [`View`](https://developer.android.com/reference/android/view/View.html) of Fragment layout\
  or null if the Fragment does not have a UI

| More Callbacks                                                                                                                        |                                                                                   |
| ------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| [**`onAttach()`**](https://developer.android.com/reference/android/app/Fragment.html#onAttach\(android.content.Context\))             | Called when Fragment is first attached to Activity                                |
| [**`onPause()`**](https://developer.android.com/reference/android/app/Fragment.html#onPause\(\))                                      | Called when Activity is paused                                                    |
| [**`onResume()`**](https://developer.android.com/reference/android/app/Fragment.html#onResume\(\))                                    | Called by Activity to resume a visible Fragment                                   |
| [**`onActivityCreated()`**](https://developer.android.com/reference/android/app/Fragment.html#onActivityCreated\(android.os.Bundle\)) | Called when Activity `onCreate()` method has returned                             |
| [**`onDestroyView()`**](https://developer.android.com/reference/android/app/Fragment.html#onDestroyView\(\))                          | Called when View previously created by `onCreateView()` is detached from Fragment |

[**`onActivityCreated()`**](https://developer.android.com/reference/android/app/Fragment.html#onActivityCreated\(android.os.Bundle\))**:** Called when the Activity onCreate() method has returned&#x20;

* Called after [`onCreateView()`](https://developer.android.com/reference/android/app/Fragment.html#onCreateView\(android.view.LayoutInflater,%20android.view.ViewGroup,%20android.os.Bundle\)) and before [`onViewStateRestored()`](https://developer.android.com/reference/android/app/Fragment.html#onViewStateRestored\(android.os.Bundle\))
* Retrieve views or restore state
* Use [`setRetainInstance()`](https://developer.android.com/reference/android/app/Fragment.html#setRetainInstance\(boolean\)) to keep Fragment instance when Activity is recreated

Use [`onDestroyView()`](https://developer.android.com/reference/android/app/Fragment.html#onDestroyView\(\)) to perform action after Fragment is no longer visible

* Called after[`onStop()`](https://developer.android.com/reference/android/app/Fragment.html#onStop\(\)) and before [`onDestroy()`](https://developer.android.com/reference/android/app/Fragment.html#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:

* Use [`getActivity()`](https://developer.android.com/reference/android/app/Fragment.html#getActivity\(\)) to get the[`Activity`](https://developer.android.com/reference/android/app/Activity.html) that started the fragment
* Find a View in the Activity layout:

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

Get Fragment by calling [`findFragmentById()`](https://developer.android.com/reference/android/app/FragmentManager.html#findFragmentById\(int\)) on  `FragmentManager`:

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

Add Fragment to back stack: [`addToBackStack(null)`](https://developer.android.com/reference/android/app/FragmentTransaction.html#addToBackStack\(java.lang.String\))

* Host `Activity` maintains back stack even after `Fragment` is removed
* Allows navigation with Back button

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