Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to reference the parent activity of a fragment?

Tags:

android

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.

like image 930
HAxxor Avatar asked Oct 29 '12 05:10

HAxxor


2 Answers

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

like image 126
James McCracken Avatar answered Nov 11 '22 14:11

James McCracken


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

like image 21
Charan Avatar answered Nov 11 '22 14:11

Charan