在 Fragment 中使用 Spinner 和 Adapter

Use Spinner and Adapter in Fragment

我在 运行 Activity 中的以下代码工作但是我在 运行 时,片段中的以下代码不起作用。我需要在 Fragment 中使用这段代码。我是初学者。请帮助我。


片段中的代码:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_filter, container, false);

    Spinner categorySpinner = (Spinner) container.findViewById(R.id.category_spinner);
    ArrayAdapter<CharSequence> categoryAdapter = ArrayAdapter.createFromResource(getContext(), R.array.cat, R.layout.row_spinner);
    categorySpinner.setAdapter(categoryAdapter);

    return view;
}

我将 getContext() 更改为 getActivity()thisthis.getActivity 但不起作用。


错误(在 categorySpinner.setAdapter(categoryAdapter 中):

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference

您正在尝试对空对象调用方法,因为您没有为您的片段获取正确的上下文。

更改以下行:

Spinner categorySpinner = (Spinner) container.findViewById(R.id.category_spinner);

收件人:

Spinner categorySpinner = (Spinner) getActivity().findViewById(R.id.category_spinner);
Spinner categorySpinner = (Spinner) view.findViewById(R.id.category_spinner);

使用视图而不是容器