Sam Sam - 18 days ago 6
Android Question

Adding selected Spinner value in a table on runtime

Is it possible to add selected spinner item in a table (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?

Answer

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...

Comments