当我在微调器中使用setOnItemSelectedListener时,会发生错误。 这是我的代码:
public class FragmentAdd extends Fragment {
private Spinner spinnerProvince;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
spinnerProvince = (Spinner) getActivity().findViewById(R.id.spinner_province);
spinnerProvince.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
return inflater.inflate(R.layout.fragment_add,container,false);
}
}
错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setOnItemSelectedListener(android.widget.AdapterView$OnItemSelectedListener)' on a null object reference
我如何解决这个问题。
答案 0 :(得分:1)
您应首先对视图进行充气,然后在充气视图上执行id绑定尝试此
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_add,container,false);
spinnerProvince = (Spinner) root.findViewById(R.id.spinner_province);
spinnerProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
return root;
}