Best practice to reference the parent activity of a fragment?

getActivity() is best. You need not maintain a variable to store (always, til app cycle!). If needed invoke the method and use! :)


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

Tags:

Android