2017-10-28 325 views
2

我在Activity工作中运行下面的代码但我在Fragment中运行下面的代码不起作用。我需要在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 

回答

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

使用视图,而不是容器

+0

这是正确的方式 谢谢... –

0

你试图调用的方法的空对象,因为你没有得到你的片段正确的上下文。

更改以下行:

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

要:

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

这么想的工作,并展现给我的错误:'java.lang中.NullPointerException:尝试在空对象引用上调用虚拟方法'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' nce' –

+0

您是否在您的xml中为该category_spinner设置了正确的活动上下文? – Miguel

+0

我编辑我的问题。请检查一下。 –