我想在片段中使用微调器,我有这个代码但没有用,我有NullPointerException
,我做错了什么?谢谢。
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Spinner spinner_idiomas = (Spinner) getActivity().findViewById(R.id.spinner_idioma);
spinner_idiomas.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Toast.makeText(getActivity(), parentView.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
return inflater.inflate(R.layout.preferencias, container, false);
答案 0 :(得分:1)
Spinner spinner_idiomas =(Spinner) 。getActivity()findViewById(R.id.spinner_idioma);
如果您要在活动中查找视图,请使用上述内容。这不是你想要的
更改为
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.preferencias, container, false);
Spinner spinner_idiomas = (Spinner) view.findViewById(R.id.spinner_idioma);
spinner_idiomas.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Toast.makeText(getActivity(), parentView.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
return view;
}