Spinner onItemSelected不起作用

时间:2017-04-07 08:45:35

标签: android android-spinner onitemselectedlistener

private Spinner spinnerMonth;

public View onCreateView(LayoutInflater inflater
        , @Nullable ViewGroup container
        , @Nullable Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    _view = inflater.inflate(R.layout.fragment_spinnerMonth, container, false);
     // Month
    spinnerMonth = (Spinner) _view.findViewById(R.id.spinnerMonth);
    spinnerMonth.setAdapter(monthAdapter);
    spinnerMonth.setSelection(_selectedMonth - 1);
    return _view;
}

private void saveData() {
    spinnerMonth.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        Log.d("month",i);        
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    });
}

我的代码如上。如果我确定一个全局Spinner,onItemSelected不起作用。如果我确定一个本地Spinner,那就是工作。为什么会这样?我需要一个全球的Spinner。

2 个答案:

答案 0 :(得分:0)

找到解决方案

public View onCreateView(LayoutInflater inflater
        , @Nullable ViewGroup container
        , @Nullable Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    _view = inflater.inflate(R.layout.fragment_spinnerMonth, container, false);
     // Month
    spinnerMonth = (Spinner) _view.findViewById(R.id.spinnerMonth);
    spinnerMonth.setAdapter(monthAdapter);
    spinnerMonth.setSelection(_selectedMonth - 1);
    spinnerMonth.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        Log.d("month",i);        
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    });
    return _view;
}

答案 1 :(得分:0)

要为微调器定义选择事件处理程序,请实现AdapterView.OnItemSelectedListener接口和相应的onItemSelected()回调方法。

spinner.setOnItemSelectedListener(new OnItemSelectedListener() 
    {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
        {
            String selectedItem = parent.getItemAtPosition(position).toString();

        } // to close the onItemSelected
        public void onNothingSelected(AdapterView<?> parent) 
        {

        }           
    });

https://developer.android.com/guide/topics/ui/controls/spinner.html