Using context in a fragment

后端 未结 30 2628
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: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.

提交回复
热议问题