将Spinner选择用作Android中的值

时间:2010-11-20 16:30:48

标签: android spinner

我想让Spinner在Android中工作。它显示正常,我可以选择列表中的任何一个选项。但是如何将其转换为字符串? 我会在下面的代码中想到'selected'将保留所选字符串,但是我得到了一个'非法修饰符,用于本地类YourItemSelectedListener; 'YourItemSelectedListener'上只允许'abstract或final'错误。 我究竟做错了什么? 非常感谢您的帮助。

Spinner spinnerFPS = (Spinner) findViewById(R.id.sp_FPS);
        ArrayAdapter adapter = ArrayAdapter.createFromResource(
                this, R.array.framesps, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerFPS.setAdapter(adapter);
        spinnerFPS.setOnItemSelectedListener(new YourItemSelectedListener());


        public class YourItemSelectedListener implements OnItemSelectedListener {

            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                String selected = parent.getItemAtPosition(pos).toString();
            }

            public void onNothingSelected(AdapterView parent) {
                // Do nothing.
            }
        }

2 个答案:

答案 0 :(得分:3)

ArrayAdapter adapter = ArrayAdapter.createFromResource(
        this, items, android.R.layout.simple_spinner_item);

您必须添加CurrentActivityName.this。这将解决问题。您无法将参数上下文传递为this。您必须放ActivityName.this

答案 1 :(得分:1)

由于您使用数组资源进行微调器创建资源句柄 使用getResources().getStringArray(R.array.framesps);

的本地数组声明

然后使用该句柄使用位置变量访问所选项目:

items[pos]

继承代码编辑:

Spinner spinnerFPS = (Spinner) findViewById(R.id.sp_FPS);
    String[] items=getResources().getStringArray(R.array.framesps);//handle to your arrays
ArrayAdapter adapter = ArrayAdapter.createFromResource(
            this, items, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerFPS.setAdapter(adapter);
    spinnerFPS.setOnItemSelectedListener(new YourItemSelectedListener());


    public class YourItemSelectedListener implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            String selected =items[pos]; // use handler to access select item
        }

        public void onNothingSelected(AdapterView parent) {
            // Do nothing.
        }
    }