Using context in a fragment

后端 未结 30 2626
Happy的楠姐
Happy的楠姐 2020-11-22 00:05

How can I get the context in a fragment?

I need to use my database whose constructor takes in the context, but getApplicationContext() and Fragmen

30条回答
  •  礼貌的吻别
    2020-11-22 00:28

    You can use getActivity() or getContext in Fragment.

    Documentation

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

    and

     /**
         * Return the {@link Context} this fragment is currently associated with.
         *
         * @see #requireContext()
         */
        @Nullable
        public Context getContext() {
            return mHost == null ? null : mHost.getContext();
        }
    

    Pro tip

    Check always if(getActivity!=null) because it can be null when fragment is not attached to activity. Sometimes doing long operation in fragment (like fetching data from rest api) takes some time. and if user navigate to another fragment. Then getActivity will be null. And you will get NPE if you did not handle it.

提交回复
热议问题