I've been working a lot with fragments lately and I was just curious as to what the best practice is for using a reference to a fragment's parent activity. Would it be better to keep calling getActivity() or have a parentActivity variable initialized on the onActivityCreated callback.
This is actually included in the official Android document on Fragments. When you need the context of the parent activity (e.g. Toast, Dialog), you would call getActivity()
. When you need to invoke the callback methods in your Fragment's interface, you should use a callback variable that is instantiated in onAttach(...)
.
public static class FragmentA extends ListFragment {
ExampleFragmentCallbackInterface mListener;
...
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mListener = (ExampleFragmentCallbackInterface ) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement ExampleFragmentCallbackInterface ");
}
}
...
}
Source
getActivity() is best. You need not maintain a variable to store (always, til app cycle!). If needed invoke the method and use! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With