Using context in a fragment

后端 未结 30 2613
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:12

    Always use the getActivity() method to get the context of your attached activity, but always remember one thing: Fragments are slightly unstable and getActivity returns null some times, so for that, always check the isAdded() method of fragment before getting context by getActivity().

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

    Since API level 23 there is getContext() but if you want to support older versions you can use getActivity().getApplicationContext() while I still recommend using the support version of Fragment which is android.support.v4.app.Fragment.

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

    I think you can use

    public static class MyFragment extends Fragment {
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
          Context context = getActivity.getContext();
    
      }
    }
    
    0 讨论(0)
  • 2020-11-22 00:15

    You can use getActivity() method to get context or You can use getContext() method .

     View root = inflater.inflate(R.layout.fragment_slideshow, container, false);
        Context c = root.getContext();
    

    I hope it helps!

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

    Another alternative approach is:

    You can get the context using:

    getActivity().getApplicationContext();
    
    0 讨论(0)
  • 2020-11-22 00:16

    getActivity() is a child of Context so that should work for you

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