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

2

13

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?

Precognition answered 10/6, 2015 at 17:4 Comment(0)
S
24

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.

Slaveholder answered 10/6, 2015 at 17:20 Comment(0)
W
8

My attempt at improving neonamu's answer:

You can define an interface like specified above, but a generic one

public interface OnListFragmentInteractionListener<T> {

      void onListFragmentInteraction(String tag, T data);
}

Then in the host activity you can implement it specifically for the type you want, or like suggested above for Object:

public class MyFragActivity implements OnListFragmentInteractionListener<Object> {
    ...

    @Override
    public void onListFragmentInteraction(String tag, Object data) {
          //do some stuff with the data
    }
}

This way when you implement the interface depending on your application's needs, maybe you can reuse this interface in another situation.

Wooley answered 29/3, 2016 at 15:36 Comment(3)
Works like a charm. Thanks a lot!Lubricant
I was wondering why you use @Override and user Neonamu does not. Do both work?Amoebic
@Amoebic yes it will work without it.BUT You should use it. the override annotation in Java is meant to be a check/verification that you are actually doing the override you think you are (it will report an error if you forget a parameter for example) without the Override you'd be simply defining a new method with same name different parameters (doing an overload ) and not implementing the interfaceWooley

© 2022 - 2024 — McMap. All rights reserved.