Best practice to reference the parent activity of a fragment?

前端 未结 3 1685
借酒劲吻你
借酒劲吻你 2020-12-16 16:04

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 bet

相关标签:
3条回答
  • 2020-12-16 16:40

    If you are in the fragment which is called from some activity, to get the reference to parent activity you can call it inside onViewCreated() or later hook methods of fragment directly by, it is just to make sure that parent activity is not null

    getActivity()
    

    If you want to really make sure you need to check first

    if (getActivity() != null){ // then your logic with getActivity()}
    
    0 讨论(0)
  • 2020-12-16 16:43

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

    0 讨论(0)
  • 2020-12-16 17:04

    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

    0 讨论(0)
提交回复
热议问题