Activity and Fragments communication

Activity and fragments communication is important when you want to update data or action. You can do communication between Activity and Fragments using interface. It’s required much time to pass data between activity and fragments or Fragments to fragments.

Activity and Fragments communication example

Communication Fragments to Activity :

The easiest way to communicate between your activity and fragments is using interfaces. The idea is basically to define an interface inside a given Fragments and let the activity implement that interface.

Once it has implemented that interface, you could do anything you want in the method it overrides.

The other important part of the interface is that you have to call the abstract method from your fragment and remember to cast it to your activity. It should catch a ClassCastException, if not done correctly.

 

Communication Activity to Fragments :

Its very easy to do, create a method in Fragments and in Activity create an instance of fragments and pass data in methods. it’s a flexible way when the fragment is already launched and Fragments want data from an Activity.

Method in fragment 

Create an instance in activity and pass data to fragment 

Maybe chance you have to another way or requirement, then you have to choose as per needs.

 

Situation: How to access a variable in activity from a fragment?

It’s a common situation when developer facing this kind of a problem during application developer. In this example, we are doing the same thing or you will get an idea of how to do it.

 

Let’s build Android app for Activity and Fragments communication

Step 1. Create new project “Build Your First Android App in Kotlin
Step 2. Add color in app>res>values>colors.xml

Step 3. Create new fragment with the resource file

Resource file “fragment_my.xml” with 2 TextView and a Button widget

Now in Fragment class, “MyFragment.java” add the following code

Step 4. Add fowling code in main_activity.xml

Step 5. Add fowling code in MainActivity.java

Step 6. Run the application, in the emulator or On your android device
Output screenshot Activity and fragments communication example

Activity and fragments communication example

Video

Download source code Activity and fragments communication example :

https://github.com/EyeHunts/ActivityFragmentcommunication

 

Note : This example (Project) is developed in Android Studio 3.0.1 ,tested on Android 7.1.1 ( Android Nougat), compile SDK version API 26: Android 8.0 (Oreo)

MinSdkVersion=”15″

TargetSdkVersion=”26″

Coding in Java


One thought on “Activity and Fragments communication

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.