Using context in a fragment

后端 未结 30 2614
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:27

    For Kotlin you can use context directly in fragments. But in some cased you will find an error like

    Type mismatch: inferred type is Context? but Context was expected

    for that you can do this

    val ctx = context ?: return
    textViewABC.setTextColor(ContextCompat.getColor(ctx, android.R.color.black))
    
    0 讨论(0)
  • 2020-11-22 00:27

    Inside fragment for kotlin sample would help someone

    textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))
    

    if you use databinding;

    bindingView.textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))
    

    Where bindingView is initialized in onCreateView like this

    private lateinit var bindingView: FragmentBookingHistoryDetailBinding
    
    bindingView = DataBindingUtil.inflate(inflater, R.layout.your_layout_xml, container, false)
    
    0 讨论(0)
  • 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.

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

    getContext() came in API 23. Replace it with getActivity() everywhere in the code.

    See if it fixes the error. Try to use methods which are in between the target and minimun API level, else this error will come in place.

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

    Use fragments from Support Library -

    android.support.v4.app.Fragment
    

    and then override

    void onAttach (Context context) {
      this.context = context;
    }
    

    This way you can be sure that context will always be a non-null value.

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

    The simple way is to use getActivity(). But I think the major confusion of using the getActivity() method to get the context here is a null pointer exception.

    For this, first check with the isAdded() method which will determine whether it's added or not, and then we can use the getActivity() to get the context of Activity.

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