如何获得片段中的上下文?

我需要使用我的数据库,其构造函数接受上下文,但getApplicationContext()和FragmentClass。这个不管用,我该怎么办?

数据库的构造函数

public Database(Context ctx)
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}

当前回答

您可以使用getActivity(),它返回与片段关联的活动。 活动是一个上下文(因为活动扩展了上下文)。

其他回答

getActivity()是Context的子元素,所以它可以为你工作

@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    context=activity;
}

另一种替代方法是:

你可以使用以下方法获取上下文:

getActivity().getApplicationContext();

正确的方法是使用

requireContext()

这个例子

ContextCompat.getColor(requireContext(), R.color.colorAccent),

里面的碎片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)