Using context in a fragment

后端 未结 30 2617
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:21

    The easiest and most precise way to get the context of the fragment that I found is to get it directly from the ViewGroup when you call onCreateView method at least here you are sure not to get null for getActivity():

    public class Animal extends Fragment { 
      Context thiscontext;
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
      {
        thiscontext = container.getContext();
    

提交回复
热议问题