How to handle multiple fragment interaction listeners in one Activity properly?

MainstreamDeveloper00 picture MainstreamDeveloper00 · Jun 10, 2015 · Viewed 7.6k times · Source

I have one Activity and six different Fragments attached to it. Each fragment has OnFragmentInteractionListener interface and activity implements all these listeners in order to receive callbacks. It looks a little messy, so I'm interested are there some patterns/ways to simplify this and make more elegant?

Answer

Neonamu picture Neonamu · Jun 10, 2015

A good solution could be use the SAME OnFragmentInteractionListener for all fragments, and use one param of each listener methods (like a TAG parameter) to identificate what fragment sent the action.

Here an example:

Make a new class and every fragment use this class

OnFragmentInteractionListener.java

public interface OnFragmentInteractionListener {
    public void onFragmentMessage(String TAG, Object data);
}

In your activity:

public void onFragmentMessage(String TAG, Object data){
    if (TAG.equals("TAGFragment1")){
        //Do something with 'data' that comes from fragment1
    }
    else if (TAG.equals("TAGFragment2")){
        //Do something with 'data' that comes from fragment2
    }
    ... 
} 

You can use Object type to pass every type of data that you want ( then, in every if, you must convert Object to type that were necessary).

Using this way, maintenance is easier than have 6 differents listeners and a method for every type of data you want to pass.

Hope this helps.