从自己的类调用片段方法



从另一个类调用片段方法的正确方法是什么

我有一个类"ParseCommands.java",如下所示:

public class ParseCommands {
public static Context context;
< call to FragmentSettings.doStuff() >
}

我想在我的Fragment:中调用doStuff()方法

public class FragmentSettings extends PreferenceFragment {
private static Activity a;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); 
}
public void doStuff(String message) {
Toast.makeText(a, message, Toast.LENGTH_SHORT).show();
}
}

我通过选项卡应用我的片段,所以我不使用片段管理器来设置它们,但我尝试了以下方法来尝试调用该方法,但似乎不起作用:

Activity act = (Activity) context;
FragmentManager fm = act.getFragmentManager();
FragmentSettings fs = (FragmentSettings) m.findFragmentById(R.xml.fragment_settings);
fs.doStuff("it actually worked!");

我试着将doStuff声明为静态,并将其称为:

FragmentSettings.doStuff

这两种方法似乎都不起作用。。。

正确的方法是什么

由于ParseCommands类中有一个上下文对象,因此可以使用LocalBroadCastManager向Fragment发送消息。您的片段必须具有BroadcastReceiver实现,并且可以从onReceive方法调用doStuff方法。

对于实现检查:如何使用LocalBroadcastManager?

最新更新