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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…