如何获得片段中的上下文?
我需要使用我的数据库,其构造函数接受上下文,但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);
}
当前回答
getActivity()是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)
我需要使用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));
理想情况下,您不应该使用全局变量。这个片段有不同的通知,其中一个是onActivityCreated。您可以在这个片段的生命周期事件中获得活动的实例。
然后:你可以解引用片段来获得activity, context或applicationcontext:
this.getActivity()会给你activity的句柄 this.getContext()会给你一个上下文句柄 this.getActivity(). getapplicationcontext()将为您提供应用程序上下文的句柄。在将它传递给db时,最好使用应用程序上下文。
你有不同的选择:
如果你的minSDK <= 21,那么你可以使用getActivity(),因为这是一个Context。 如果你的minSDK是>=23,那么你可以使用getContext()。
如果您不需要支持旧版本,则使用getContext()。
getActivity()是Context的子元素,所以它可以为你工作