
Communication is always important for developers. Sometimes we need to communicate between two fragments. Two fragments should not communicate directly as fragment is a re-useable UI component and should be built independently.
Now, we will see how we can communicate between two fragments using an interface.
Suppose, we have created two fragments in an activity named FragmentA
and FragmentB
. We want to perform some task in FragmentA
after FragmentB
has inserted some data in database.
First, we will define an interface in FragmentB
.
public class FragmentB extends Fragment {
private Callback callback;
public void setCallback(Callback callback) {
this.callback = callback;
}
public interface Callback {
void performSomeTask();
}
}
FragmentB
Now, when the FragmentB
is attached to the MainActivity
, we will do the following :
public class MainActivity extends AppCompatActivity
implements FragmentB.Callback {
@Override
public void onAttachFragment(Fragment fragment) {
if (fragment instanceof FragmentB) {
FragmentB fragmentB = (FragmentB) fragment;
fragmentB.setCallback(this);
}
}
}
MainActivity
After insertion some data in database in FragmentB
, we will use the callback interface to send message in MainActivity
public class FragmentB extends Fragment {
//...
private void insertDataOnDB() {
//...
//after insertion complete
callback.performSomeTask();
}
}
MainActivity
Now, we will implement the Callback
interface in MainActivity
. Callback
event comes here from FragmentB
after inserting into database. Here, we will perform the task in FragmentA
through the method doTaskOnCallback
of FragmentA
. For this, we will find the FragmentA
by its Tag and perform tasks on FragmentA
.
public class MainActivity extends AppCompatActivity
implements FragmentB.Callback {
@Override
public void performSomeTask() {
//when creating FragmnetA from MainActivity, we will give
//it a tag "fragmentA"
FragmentA fragmentA = (FragmentA) getSupportFragmentManager()
.findFragmentByTag("fragmentA");
if(fragmentA != null) {
fragmentA.doTaskOnCallback();
}
}
}
Callback
interface in MainActivity
That's all.