如何获得片段中的上下文?
我需要使用我的数据库,其构造函数接受上下文,但getApplicationContext()和FragmentClass。这个不管用,我该怎么办?
数据库的构造函数
public Database(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
如何获得片段中的上下文?
我需要使用我的数据库,其构造函数接受上下文,但getApplicationContext()和FragmentClass。这个不管用,我该怎么办?
数据库的构造函数
public Database(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
当前回答
在Kotlin中,你可以这样使用: .applicationContext requireActivity ()
其他回答
public class MenuFragment extends Fragment implements View.OnClickListener {
private Context mContext;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragmentMenuBinding binding=FragmentMenuBinding.inflate(inflater,container,false);
View view=binding.getRoot();
mContext=view.getContext();
return view;
}
}
当覆盖onCreateView时,你也可以从inflater参数获得上下文。
public static class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* ... */
Context context = inflater.getContext();
/* ... */
}
}
我想你可以用
public static class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getActivity.getContext();
}
}
您可以使用getActivity(),它返回与片段关联的活动。 活动是一个上下文(因为活动扩展了上下文)。
注意:如果getActivity()在相应片段的onAttach之前被调用,它会返回null。
2.or
最简单和最精确的方法来获得片段的上下文,我发现是直接从ViewGroup当你调用onCreateView方法,至少在这里你肯定不会得到空getActivity():
public class Animal extends Fragment {
Context thiscontext;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState)
{
thiscontext = container.getContext();
//...
//...
//...
}
在kotlin中只使用activity而不是getActivity()