如何在片段和未附加的 Activity 之间进行通信?

How to communicate between a Fragment and an Activity to which it is not attached?

我想在片段上的 onClick 事件后对 Activity 执行一些操作。

我只发现了如何使用 getActivity() 在片段和片段所附加的 Activity 之间进行通信,这不是我的情况。

正如其他人所说,您必须使用广播或服务.....

但是:

最简单、最快的方法是:

创建这两个 类::

全局变量:

public class Globals {

private static final Globals instance = new Globals();
private GlobalVariables globalVariables = new GlobalVariables();

private Globals() {
}

public static Globals getInstance() {
    return instance;
}

public GlobalVariables getValue() {
    return globalVariables;
}

}

和全局变量::

public class GlobalVariables {
    public Activity receiverActivity;
}

不在接收器中 activity::

Globals.getInstance().getValue().receiverActivity = this;

发件人现在可以做任何事情了!例如从接收器 activity:

调用 public 方法
Globals.getInstance().getValue().doSomething();

基本不推荐,但是效果很好。 :D

您必须创建一个您的 activity 实现的接口。 BroadcastReceivers 确实有其优势,但通过回调解决这个问题非常简单直接。

这是一个例子。我们给 Activity 一个字符串并让它 return 一个整数:

public interface IMyStringListener{
public Integer computeSomething(String myString);
}

接口可以在片段中定义,也可以在单独的文件中定义。接下来你的 Activity 实现接口。

public class MyActivity implements IMyStringListener{

 @Override
 public Integer computeSomething(String myString){
   /** Do something with the string and return your Integer instead of 0 **/ 
   return 0;
  }

}

然后在您的片段中您将拥有一个 MyStringListener 变量,您将在片段 onAttach(Activity activity) 方法中设置侦听器。

public class MyFragment {

    private MyStringListener listener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            listener = (MyStringListener) activity;
        } catch (ClassCastException castException) {
            /** The activity does not implement the listener. */
        }
    }

}

使用委托: 一个 createView 触发委托,并在 activity

中创建侦听器

试试这个: Fragment-Fragment communication in Android

只是委托函数

对于超级简单的解决方案,使用片段触发您 activity class 中的方法,该方法使用意图调用所需的 activity。

编辑:查看下面的评论以获得更多帮助。