本文翻译自: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? 我需要使用其构造函数接受上下文的数据库,但getApplicationContext()
和FragmentClass.this
不起作用,该怎么办?
Database constructor 数据库构造函数
public Database(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
#1楼
参考:https://stackoom.com/question/YTAy/在片段中使用上下文
#2楼
To do as the answer above, you can override the onAttach
method of fragment: 为此,您可以覆盖片段的onAttach
方法:
public static class DummySectionFragment extends Fragment{
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
DBHelper = new DatabaseHelper(activity);
}
}
#3楼
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()
: 获取我发现的片段上下文的最简单,最精确的方法是,至少在这里,当您调用onCreateView
方法时,直接从ViewGroup
获取片段:请确保不会为getActivity()
获得null:
public class Animal extends Fragment {
Context thiscontext;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
thiscontext = container.getContext();
#4楼
始终使用getActivity()方法获取所附加活动的上下文,但始终要记住一件事:片段稍微不稳定,并且getActivity
有时会返回null,因此,在获取上下文之前,请务必先检查片段的iwego()方法getActivity()
。
#5楼
Another alternative approach is: 另一种替代方法是:
You can get the context using: 您可以使用以下方式获取上下文:
getActivity().getApplicationContext();
#6楼
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
context=activity;
}