Using context in a fragment

后端 未结 30 2631
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:17
    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        context=activity;
    }
    
    0 讨论(0)
  • 2020-11-22 00:17

    Also you can use:

    inflater.getContext();
    

    but I would prefer to use

    getActivity()
    

    or

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

    You could also get the context from the inflater parameter, when overriding onCreateView.

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

    to get the context inside the Fragment will be possible using getActivity() :

    public Database()
    {
        this.context = getActivity();
        DBHelper = new DatabaseHelper(this.context);
    }
    
    • Be careful, to get the Activity associated with the fragment using getActivity(), you can use it but is not recommended it will cause memory leaks.

    I think a better aproach must be getting the Activity from the onAttach() method:

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        context = activity;
    }
    
    0 讨论(0)
  • 2020-11-22 00:20

    Ideally, you should not need to use globals. The fragment has different notifications, one of them being onActivityCreated. You can get the instance of the activity in this lifecycle event of the fragment.

    Then: you can dereference the fragment to get activity, context or applicationcontext as you desire:

    this.getActivity() will give you the handle to the activity this.getContext() will give you a handle to the context this.getActivity().getApplicationContext() will give you the handle to the application context. You should preferably use the application context when passing it on to the db.

    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题