如何获得片段中的上下文?
我需要使用我的数据库,其构造函数接受上下文,但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样品将帮助某人
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)
其他回答
你可以调用getActivity()或者,
public void onAttach(Context context) {
super.onAttach(context);
this.activity = (CashActivity) context;
this.money = this.activity.money;
}
对于Kotlin,您可以直接在片段中使用上下文。但在某些情况下,你会发现这样的错误
类型不匹配:推断类型是上下文?但背景是意料之中的
你可以这样做
val ctx = context ?: return
textViewABC.setTextColor(ContextCompat.getColor(ctx, android.R.color.black))
另一种替代方法是:
你可以使用以下方法获取上下文:
getActivity().getApplicationContext();
我想你可以用
public static class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getActivity.getContext();
}
}
要做到如上的答案,你可以重写fragment的onAttach方法:
public static class DummySectionFragment extends Fragment{
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
DBHelper = new DatabaseHelper(activity);
}
}