Using context in a fragment

后端 未结 30 2681
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().

提交回复
热议问题