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

前端 未结 8 730
深忆病人
深忆病人 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条回答
  •  自闭症患者
    2020-12-02 15:51

    /**
         * Return the {@link Context} this fragment is currently associated with.
         */
        public Context getContext() {
            return mHost == null ? null : mHost.getContext();
        }
    
        /**
         * Return the {@link FragmentActivity} this fragment is currently associated with.
         * May return {@code null} if the fragment is associated with a {@link Context}
         * instead.
         */
        final public FragmentActivity getActivity() {
            return mHost == null ? null : (FragmentActivity) mHost.getActivity();
        }
    

    from source code, we can find that when a fragment is attached to an Activity, getContext returns null. While getActivity returns null when a fragment is attached to context instead

提交回复
热议问题