如何正确处理一个 Activity 中的多个片段交互监听器?

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

我附有一个 Activity 和六个不同的 Fragments。每个片段都有 OnFragmentInteractionListener 接口和 activity 实现所有这些侦听器以接收回调。它看起来有点乱,所以我很感兴趣是否有一些 patterns/ways 可以简化它并使其更优雅?

一个好的解决方案可以是对所有片段使用相同的 OnFragmentInteractionListener,并使用每个侦听器方法的一个参数(如 TAG 参数)来识别发送操作的片段。

举个例子:

制作一个新的 class 并且每个片段都使用这个 class

OnFragmentInteractionListener.java

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

在你的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
    }
    ... 
} 

您可以使用 Object 类型来传递您想要的每种数据类型(然后,在每个 if 中,您必须将 Object 转换为所需的类型)。

使用这种方式,维护起来比有 6 个不同的侦听器和一个方法要传递的每种类型的数据更容易。

希望对您有所帮助。

我的改进尝试

您可以像上面指定的那样定义一个接口,但是一个通用接口

public interface OnListFragmentInteractionListener<T> {

      void onListFragmentInteraction(String tag, T data);
}

然后在主机 activity 中,您可以专门为您想要的类型实现它,或者像上面建议的对象:

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

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

这样当您根据应用程序的需要实现接口时,也许您可​​以在其他情况下重用该接口。