在运行时在表中添加选定的Spinner值

时间:2011-04-06 12:07:12

标签: android spinner

是否可以在按钮单击时在textview中添加选定的微调器项目(动态生成)。 通常我使用此代码:

spinner=new String[5];
spinner[0]="1";
spinner[1]="2";
spinner[2]="3";
Spinner spn = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, spinner);
        spn.setAdapter(adapter);

但是在表格中添加所选值时该怎么办?

2 个答案:

答案 0 :(得分:0)

填充Spinner后,使用OnItemSelectedListener在Spinner中获取Selected值。

以下是在Spinner中获取Selected值的代码:

spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub
             selectedspinnervalue =spinner.getSelectedItem().toString();
        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });

其中selectedspinnervalue包含所选值..

然后在Table ..中添加值。

答案 1 :(得分:0)

你需要听Spinner的OnItemSelected事件。并且不要忘记为下拉项设置布局!所以按顺序:

  1. 像正确使用的那样设置适配器:spn.setAdapter(adapter);
  2. 设置下拉项目视图:spn.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  3. 挂钩OnItemSelected事件:
  4. spn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){

            @Override
            public void onItemSelected(AdapterView<?> adapter, View arg1,
                    int position, long arg3) {
                // gets called when the user selects an item
                TextView txt = (TextView)findViewById(R.id.your_textview_id);
                txt.setText((String)adapter.getItemAtPosition(position));
            }
    
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // what to do when nothing is selected
            }
        });
    

    就是这样......