Using context in a fragment
How can I get the context in a fragment?
I need to use my database whose constructor takes in the context, but getApplicationContext()
and FragmentClass.this
don't work so what can I do?
Database constructor
public Database(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
You can use getActivity()
, which returns the activity associated with a fragment.
The activity is a context (since Activity extends Context).
要做到上面的答案,你可以重写片段的onAttach
方法:
public static class DummySectionFragment extends Fragment{
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
DBHelper = new DatabaseHelper(activity);
}
}
始终使用getActivity()方法获取所连接活动的上下文,但始终记住一件事情:片段稍微不稳定,并且getActivity
有时会返回null,因此,在获取上下文之前,始终检查片段的isAdded()方法getActivity()
。
上一篇: 为旧版Android应用添加片段
下一篇: 在片段中使用上下文