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

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

数据库的构造函数

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

当前回答

当覆盖onCreateView时,你也可以从inflater参数获得上下文。

public static class MyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
        /* ... */
        Context context = inflater.getContext();
        /* ... */
    }
}

其他回答

androidx.fragment.app.Fragment

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

返回片段当前关联的Context。

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

在kotlin中只使用activity而不是getActivity()

你有不同的选择:

如果你的minSDK <= 21,那么你可以使用getActivity(),因为这是一个Context。 如果你的minSDK是>=23,那么你可以使用getContext()。

如果您不需要支持旧版本,则使用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(),它返回与片段关联的活动。 活动是一个上下文(因为活动扩展了上下文)。