开发者

Adding selected Spinner value in a table on runtime

Is it possible to add selected spinner item in a ta开发者_C百科ble (which is generating dynamically) in textview on button click. Generally I use this code:

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);

but what to do when to add the selected value in table?


you need to listen to the Spinner's OnItemSelected event. And don't forget to set the layout for the drop-down items! So in order:

  1. Set the Adapter like you did correctly: spn.setAdapter(adapter);
  2. Set the drop-down item view: spn.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  3. Hook on the OnItemSelected event:

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
        }
    });

That's it...


After the Spinner is populated get the Selected value in Spinner by using OnItemSelectedListener.

Here is the code to get the Selected value in Spinner :

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
        }
    });

In which selectedspinnervalue contains the selected value..

Then you add the value in Table..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜