在两个片段之间进行通信

-1 java android communication android-fragments android-activity

我有两个扩展Fragment的类,两个都在同一个Activity中,我想在另一个片段类中按下按钮时在一个片段类中触发一个方法,我知道这可以使用接口或意图来完成。我这样做的代码示例。提前致谢

Luc*_*Luc 5

:D

在此示例中,FragmentA调用通知。

INotifier

public interface INotifier {
    public void notify(Object data);
}
Run Code Online (Sandbox Code Playgroud)

实用程序

public class Utils {
    public static INotifier notifier;
}
Run Code Online (Sandbox Code Playgroud)

片段A

public FragmentA extends Fragment {

   public void onCreateView(...) {

   }

   public void inSomeMethod() {
        if (Utils.notifier != null) {
           Utils.notifier.notify(data);
        }
   }
}
Run Code Online (Sandbox Code Playgroud)

片段B

public FragmentB extends Fragment implements INotifier {

   public void onCreateView(...) {
       Utils.notifier = this;   
   }

   @Override
   public void notify(Object data) {
       // handle data
   }
}
Run Code Online (Sandbox Code Playgroud)