在Android中,我试图用监听器获取所选的Spinner值。

获得转轮价值的最佳方法是什么?


当前回答

将setOnItemSelectedListener添加到spinner引用中,并获得这样的数据

 mSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
            selectedSize=adapterView.getItemAtPosition(position).toString();

其他回答

View view =(View) getActivity().findViewById(controlId);
Spinner spinner = (Spinner)view.findViewById(R.id.spinner1);
String valToSet = spinner.getSelectedItem().toString();

将setOnItemSelectedListener添加到spinner引用中,并获得这样的数据

 mSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
            selectedSize=adapterView.getItemAtPosition(position).toString();
Spinner mySpinner = (Spinner) findViewById(R.id.your_spinner);
String text = mySpinner.getSelectedItem().toString();

如果你已经知道项目是一个字符串,我更喜欢:

String itemText = (String) mySpinner.getSelectedItem();

在一个你知道是字符串的对象上调用toString()似乎比仅仅将对象转换为字符串更迂回。

当某些东西被选中时,Spinner应该触发一个"OnItemSelected"事件:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        Object item = parent.getItemAtPosition(pos);
    }
    public void onNothingSelected(AdapterView<?> parent) {
    }
});