如何获得片段中的上下文?
我需要使用我的数据库,其构造函数接受上下文,但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);
}
当前回答
当覆盖onCreateView时,你也可以从inflater参数获得上下文。
public static class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* ... */
Context context = inflater.getContext();
/* ... */
}
}
其他回答
在Kotlin中,你可以这样使用: .applicationContext requireActivity ()
里面的碎片kotlin样品将帮助某人
textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))
如果你使用数据绑定;
bindingView.textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))
在onCreateView中bindingView是这样初始化的
private lateinit var bindingView: FragmentBookingHistoryDetailBinding
bindingView = DataBindingUtil.inflate(inflater, R.layout.your_layout_xml, container, false)
要做到如上的答案,你可以重写fragment的onAttach方法:
public static class DummySectionFragment extends Fragment{
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
DBHelper = new DatabaseHelper(activity);
}
}
始终使用getActivity()方法获取附加活动的上下文,但始终记住一件事:片段有点不稳定,getActivity有时返回null,因此,在通过getActivity()获取上下文之前,始终检查片段的isAdded()方法。
我需要使用arrayAdapter IN片段的上下文,当我使用getActivity错误发生时,但当我用getContext替换它时,它为我工作
listView LV=getView().findViewById(R.id.listOFsensors);
LV.setAdapter(new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1 ,listSensorType));