Getting an Activity and a Fragment to Interact
Tags: android, java, kotlin, tutorial
Published: 2022-09-07 13:32:59


There are two ways activities and fragments interact. It's either the actvity calls the methods in its fragments or the fragment calls the methods in its parent activity.
When an activity calls the methods of its fragments, it can pass data into and receive data from the fragments through the fragment's methods. The same goes for when fragments call methods on their activities. Now let's get into it.

#Activity to Fragment Communication


For an activity to communicate with its fragment, it needs a reference(or pointer) to the fragment. You get this reference to the fragment by calling the method `findFragmentById()` on the result of calling either `getFragmentManager()` or `getSupportFragmentManager()`.
If we had a fragment called _DemoFragment_ with an id of _demofragment_, we would get a reference to it with the code below:

```
FragmentManager fragmentManager = getSupportFragmentManager();
DemoFragment demoFragment = (DemoFragment)fragmentManager.findFragmentById(R.id.demofragment);
```

**Code breakdown**
Calling the function `getSupportFragmentManager()` returns a `FragmentManager` instance. That instance has a method named `findFragmentById()`.

> It's important to know that the `id` of a fragment must be assigned in the `<fragment/>` tag in the activity's xml layout file. This way, one fragment can have different ids in different activities.

When you call the method `findFragmentById` on the fragment manager, you need to type-cast it as the fragment class you want. The result of calling this method will be a reference to the fragment.

When the activity has that reference to the fragment, it can access all its public fields and properties, and call all its public methods. That is how an activity can communicate with a fragment.

#Fragment to Activity Communication

For a fragment to communicate with its parent activity, it needs to get a reference to its activity. 
Assuming we have an activity named _DemoActivity_ and we want to call one of its public methods named _demoMethod()_, we can do the job with the code snippet below:

```
((DemoActivity)getActivity()).demoMethod();
```

**Code breakdown**

To explain the code, let's divide it into two parts. Everything before the dot( **.** ) is the first part and everything after it is the second part. Let's look at the first part.

`((DemoActivity)getActivity())`:
In this part, we are calling the method `getActivity()` and converting it to an instance of our activity with type-casting. The result we'll get from this operation will be a reference to our activity. Now let's look at the second part.

`demoMethod()`:
This is a private method defined in our DemoActivity class. We are calling it through the activity reference we just got.

#Fragment Lifecycle Methods


Fragment lifecycle methods are linked to Activity lifecycle methods. This is a list of the fragment lifecycle methods:

`onAttach(Context)`: This method is called when a fragment is associated with a context

`onCreate(Bundle)`: This method is the fragment's equivalent ot onCreate().

`onCreateView(LayoutInflater, ViewGroup, Bundle)`: This is the method that's called to inflate the fragment's view.

`onActivityCreated(Bundle)`: This method is called when the parent activity's `onCreate` method has completed.

`onStart()`: is called when the fragment is created fully in the background.

`onResume()`: is called when the fragment becomes visible in the foreground.

`onPause()`: is called when a fragment leaves the foreground.

`onStop()`: is called when the fragment stops being visible to the user (when it enters the background)

`onDestroyView`: This method is called when the UI of the frgament is destroyed. It gives the developer the chance to clear any resources that are associated with the fragment's view.

`onDestroy()`: This method is used to clear any other resources associated with the fragment's class.

`onDetach()`: This method is called when the fragment is disassociated with the activity.

The diagram below shows how the fragment lifecycle relates to the activity lifecycle and the points at which their lifecycles intersect. The fragment lifecycle callbacks are on the right.

![Android fragment and activity lifecycle callbacks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/46a0onznelwyckoo67v2.png)

The `Fragment` class doesn't implement the `Context` interface so a fragment isn't a type of context, and therefore doesn't have access to global information about the app environment. For fragments to access this data, they must use the context of other objects such as their parent activity.

**_[Previous article: Android Fragments](https://dev.to/petemode/android-fragments-1gjm)_**
**_Coming up next: List Fragments_**