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

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

数据库的构造函数

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

当前回答

最简单和最精确的方法来获得片段的上下文,我发现是直接从ViewGroup当你调用onCreateView方法,至少在这里你肯定不会得到空getActivity():

public class Animal extends Fragment { 
  Context thiscontext;
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
  {
    thiscontext = container.getContext();

其他回答

requireContext()方法是最简单的选项

requireContext()

例子

MyDatabase(requireContext())

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

关于你的片段

((Name_of_your_Activity) getActivity()).helper

对经济活动

DbHelper helper = new DbHelper(this);

androidx.fragment.app.Fragment

@NonNull
public final android.content.Context requireContext()

返回片段当前关联的Context。

自: getActivity和Context可以为空,最好使用requireContext(),因为它不能为空。

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