Reputation: 119
What is the correct way of calling a fragment method from another class?
I have a class ‘ParseCommands.java’ as such:
public class ParseCommands {
public static Context context;
< call to FragmentSettings.doStuff() >
}
I would like to call the method doStuff() in my Fragment:
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();
}
}
I apply my fragments via tabs so I don’t use the fragment manager to set them up, however I’ve tried the following to try to call the method but it doesn’t seem to work:
Activity act = (Activity) context;
FragmentManager fm = act.getFragmentManager();
FragmentSettings fs = (FragmentSettings) m.findFragmentById(R.xml.fragment_settings);
fs.doStuff("it actually worked!");
and I’ve tried declaring doStuff as static and calling it like:
FragmentSettings.doStuff
Both methods don’t seem to work...
What is the correct way of doing this?
Upvotes: 0
Views: 686
Reputation: 8245
Since you have a context object in the ParseCommands class you can use the LocalBroadCastManager to send a message to your Fragment. Your fragment will have to have a BroadcastReceiver implementation and from the onReceive method you can call the doStuff method.
For an implementation check out: how to use LocalBroadcastManager?
Upvotes: 1