Now that you have two Fragments – a ListFragment and a Detail Fragment, its time for you to call the Detail Fragment from ListFragment.
Let’s understand the Fragment Communication concepts.
Suppose you have a List FragmentA which displays a List of Items. And on click of an item in the list you want to display another FragmentB.
Sounds simple ! Call the FragmentB from the FragmentA. But the catch here is that we want the two Fragments to be unaware of each other. So that they can be used with any Activity independently.
The idea here is that Fragment A will invoke Fragment B via the Activity class. And in order to decouple Fragment A and the Activity we will introduce an Interface.
Confused ? Ok, let me share an example to make this clear.
Here is some sample code
MyActivityClass implements FragmentAInterface{
callFragmentB(){
//Code to call FragmentB
}
}
FragmentA{
FragmentAInterface fragmentAInterface;
interface FragmentAInterface{
callFragmentB();
}
onItemClick(){
fragmentAInterface.callFragmentB();
}
onAttach(Activity activity){
fragmentAInterface = (FragmentAInterface) activity;
}
}
FragmentB{
}
Now what is going on here?
Understanding the Code
The FragmentA defines an interface FragmentAInterface which has one method callFragmentB.
Your Activity class MyActivityClass implements this interface and defines callFragmentB method. In which it calls FragmentB.
Now when a user clicks on an item in FragmentA the onItemClick method is called. We want this method to trigger the MyActivityClass -> callFragmentB method.
So what we do is we create a reference of the FragmentAInterface “fragmentAInterface” and assign it the Activity in onAttach method. Remember the Fragment Lifecycle ?
So this is how it works. And you can use this principle to implement such functionality.
Source Code available here
Why the activity uses explicit type casting to interface in the onattach method
Thanks
LikeLike