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

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

数据库的构造函数

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

当前回答

要做到如上的答案,你可以重写fragment的onAttach方法:

public static class DummySectionFragment extends Fragment{
...
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        DBHelper = new DatabaseHelper(activity);
    }
}

其他回答

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

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

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

我需要使用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));

另一种替代方法是:

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

getActivity().getApplicationContext();
public class MenuFragment extends Fragment implements View.OnClickListener {
    private Context mContext;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        FragmentMenuBinding binding=FragmentMenuBinding.inflate(inflater,container,false);
        View view=binding.getRoot();
        mContext=view.getContext();
        return view;
    }
}