Android Inter Fragment Communication

In this tutorial android inter fragment communication is explained. Fragments in android are utilized to fully use screen area of the mobile device.  Our final target is to make an application that will have one fragment in the activity at the time when the mobile device is in vertical position, and have more then one fragment when the mobile device is in horizontal position. So far, we will focus on more simple example in which we have two fragments inside one activity all the time. So in here, one fragment communicating with other fragments example in android is given. Let’s start new android project and add two fragments inside. Then, give no id to the fragments in their XML. Instead, fragments will have id inside of XML of the only activity inside the project. Now, let’s call upper fragment as “Upper”, and lower fragment as “Lower”.  Then set background color of “Upper” to blue (as the color of the sky) and set background color of the “Lower” to green (as the color of the grass), in order to make the difference in appearance. Then put an button in “Upper” fragment, and one text view in “Lower” fragment. Change fragment layout on both fragments from <FrameLayout to <RelativeLayout. Here is XML code for “Upper” fragment:

fragment-upper-xml

And here is XML code for “Lower” fragment:

fragment-lower-xml

Now, we will statically add this two fragments in XML of main activity.

add-upper-fragment-to-main-activity-xml

When we start our application, we obtain something like this.

main-activity-with-upper-and-lower-fragment

But we would like to have no margins, and to cover all width of the screen. So make following changes:

<fragment

android:layout_width=“wrap_content”

to
<fragment

android:layout_width=”match_parent”

main-activity-full-witdth-with-margins

We have now full width covered, but with margins. Let’s remove them.

delete-margins-in-main-xml

After removing margins, XML code of content_main is

content-main-wihout-margins-xml

Now, we want to allow fragments to communicate each other. Note: they can communicate directly, but it is very bad practice since this way of communication is called coupling, and this is something that we want to avoid by any means, because when we rotate the mobile device, directly called fragment will break the application

Android-fragment-has-stopped

In order to make application stable, we need to use interface class that will provide inter fragment communication channel that will be stable for use, and fragments will be reusable, if there is no direct reference of one fragment in another.

You can download fragment communicating with other fragments example

External links:

Android Inter Fragment Communication on YouTube
Android Inter Fragment Communication on Developer
Android Inter Fragment Communication on Stackoverflow

Posted in android Tagged with: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*