android Spinner点击事件处理

时间:2024-10-23 07:45:05

使用Spinner处理item的点击事件出现的错误
代码:

spinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //获取spinner选中的文本
                String cardNumber = Main2Activity.this.getResources().getStringArray(R.array.spinner_main_arr)[position];
                Toast.makeText(Main2Activity.this, "" + cardNumber, Toast.LENGTH_SHORT).show();
            }
        });

spinner的配置数据:在values文件下建立一个文件,自定义名称并写上下面代码

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="spinner_main_arr">
        <item>AAAA</item>
        <item>BBBB</item>
    </string-array>
</resources>

运行程序出现以下的错误

 Caused by: : setOnItemClickListener cannot be used with a spinner.
    at (:566)
    at .(:47)
错误说明 setOnItemClickListener 不能和spinner 一起使用,所以找了一个替代的方法,叫做setOnItemSelectedListener。
解决问题的代码:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String cardNumber = Main2Activity.this.getResources().getStringArray(R.array.spinner_main_arr)[position];
                Toast.makeText(Main2Activity.this, "" + cardNumber, Toast.LENGTH_SHORT).show();
            }

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

            }
        });