Using context in a fragment

后端 未结 30 2654
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:23

    You have different options:

    • If your minSDK <= 21, then you can use getActivity(), since this is a Context.
    • If your minSDK is >=23, then you can use getContext().

    If you don't need to support old versions then go with getContext().

    0 讨论(0)
  • 2020-11-22 00:23

    On you fragment

    ((Name_of_your_Activity) getActivity()).helper
    

    On Activity

    DbHelper helper = new DbHelper(this);
    
    0 讨论(0)
  • 2020-11-22 00:24

    You can use getActivity(), which returns the activity associated with a fragment.
    The activity is a context (since Activity extends Context).

    0 讨论(0)
  • 2020-11-22 00:24

    With API 29+ on Kotlin, I had to do

    activity?.applicationContext!!
    

    An example would be

    ContextCompat.getColor(activity?.applicationContext!!, R.color.colorAccent),
    
    0 讨论(0)
  • 2020-11-22 00:25

    Previously I'm using onAttach (Activity activity) to get context in Fragment

    Problem

    The onAttach (Activity activity) method was deprecated in API level 23.

    Solution

    Now to get context in Fragment we can use onAttach (Context context)

    onAttach (Context context)

    • Called when a fragment is first attached to its context. onCreate(Bundle) will be called after this.

    Documentation

    /**
     * Called when a fragment is first attached to its context.
     * {@link #onCreate(Bundle)} will be called after this.
     */
    @CallSuper
    public void onAttach(Context context) {
        mCalled = true;
        final Activity hostActivity = mHost == null ? null : mHost.getActivity();
        if (hostActivity != null) {
            mCalled = false;
            onAttach(hostActivity);
        }
    }
    

    SAMPLE CODE

    public class FirstFragment extends Fragment {
    
    
        private Context mContext;
        public FirstFragment() {
            // Required empty public constructor
        }
    
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            mContext=context;
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rooView=inflater.inflate(R.layout.fragment_first, container, false);
    
            Toast.makeText(mContext, "THIS IS SAMPLE TOAST", Toast.LENGTH_SHORT).show();
            // Inflate the layout for this fragment
            return rooView;
        }
    
    }
    

    NOTE

    We can also use getActivity() to get context in Fragments but getActivity() can return null if the your fragment is not currently attached to a parent activity,

    0 讨论(0)
  • 2020-11-22 00:26

    requireContext() method is the simplest option

    requireContext()
    

    Example

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