What is different between getContext and getActivity from Fragment in support library?

前端 未结 8 775
深忆病人
深忆病人 2020-12-02 15:39

What is different between getContext() and getActivity() from Fragment in support library?

Do they always return the same obje

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 15:41

    So far, the only provided implementation of FragmentHostCallback (in the OS and the support library) always returns the same value for both getContext() and getActivity().

    However, the other constructors of FragmentHostCallback suggest that in future implementations, we may get:

    • A null Activity and a non-null Context which is not an Activity. This looks improbable but we can imagine that fragments could be used outside Activities in the future, or be fully sandboxed.
    • A non-null Activity and a non-null Context which is not the same instance as the Activity. For example, Context could be a ContextThemeWrapper.

    Conclusion: when you can, use getContext(). When you need Activity-specific calls, use getActivity().

提交回复
热议问题