Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spinner is not working in android

Spinner is not working. Here is my code:

public class second extends Activity{   
    Spinner spin;
    String[] str;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);        
        spin = (Spinner) findViewById(R.id.spin);
        str = new String[] {"bike","car"};      
        spin.setAdapter(new ArrayAdapter<CharSequence>(this, android.R.layout.simple_dropdown_item_1line, str));    

        spin.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> adapter, View view, int pos,
                long id) {
            // TODO Auto-generated method stub

            String data= spin.getItemAtPosition(pos).toString();
            Toast.makeText(second.this, data, Toast.LENGTH_SHORT).show();
               }    
        });
    }
}
like image 455
SilentKiller Avatar asked Dec 04 '22 20:12

SilentKiller


1 Answers

The only mistake you made is you have set different event listener..

The Listener OnItemClickListener is for ListView..

For Spinner you have to set OnItemSelectedListener ..

Try replacing OnItemClickListener to setOnItemSelectedListener like :

spin.setOnItemSelectedListener (new OnItemSelectedListener() {

    public void onItemClick(AdapterView<?> adapter, View view, int pos,
            long id) {
        // TODO Auto-generated method stub

        String data= spin.getItemAtPosition(pos).toString();
        Toast.makeText(second.this, data, Toast.LENGTH_SHORT).show();
    }

});
like image 95
Kartik Domadiya Avatar answered Dec 11 '22 11:12

Kartik Domadiya