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

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

数据库的构造函数

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

当前回答

在Kotlin中,你可以这样使用: .applicationContext requireActivity ()

其他回答

关于你的片段

((Name_of_your_Activity) getActivity()).helper

对经济活动

DbHelper helper = new DbHelper(this);

获取片段上下文的安全方法

if(isAdded){
requireActivit();//this is your context
}

您可以使用getActivity()方法来获取上下文或 您可以使用getContext()方法。

View root = inflater.inflate(R.layout.fragment_slideshow, container, false);
Context c = root.getContext();

我希望这能有所帮助!

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

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

正确的方法是使用

requireContext()

这个例子

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