spinner的setOnItemSelectedListener未执行

时间:2015-04-07 04:00:56

标签: android

我正在以这种方式创建一个微调器:

spinnerShared = (Spinner) findViewById(R.id.spinnerShared);
    Resources res = getResources();
    CustomAdapter customAdapter = new CustomAdapter(this,
            R.layout.spinner_row, arryList, res);
    spinnerShared.setAdapter(customAdapter);

我希望以这种方式获得选定的价值:

    spinnerShared.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {
    Toast.makeText(StartActivity.this, "onItemSelected executed", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

我应该收到消息&#34; onItemSelected执行&#34;在吐司。但我没有收到消息。

2 个答案:

答案 0 :(得分:2)

试试这个......

public class MainActivity extends Activity {
    Spinner s1;
    String[] sports = {
            "Cricket",
            "Footbale",
            "Hockey",
            "Table Tennis",

    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //---Spinner View---
        s1 = (Spinner) findViewById(R.id.spinner1);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            this, android.R.layout.simple_spinner_item, sports);
        s1.setAdapter(adapter);

        s1.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1, 
            int arg2, long arg3) {
                int index = s1.getSelectedItemPosition(); Toast.makeText(getBaseContext(),
                    "You have selected item : " + sports[index], 
                    Toast.LENGTH_SHORT).show();
            }
            public void onNothingSelected(AdapterView<?> arg0) {
            } 
        });
    }

}

答案 1 :(得分:0)

解决您的问题很简单

当您单击微调器的任何项时,

setOnItemSelectedListener将执行 不是当你点击按钮时,所以只是尝试改变微调值......