Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listener on a Spinner

This code adds strings to a Spinner from a list.
How do I implement a listener so that I can get the string that is clicked or tapped from the Spinner?

spinner = (Spinner) findViewById(R.id.spinner);
List<String> list = new ArrayList<String>();

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, list);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner.setAdapter(dataAdapter);
like image 213
Boneyflesh Avatar asked Dec 02 '22 12:12

Boneyflesh


2 Answers

You can use this code

 spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
    {
        String selectedItem = parent.getItemAtPosition(position).toString(); //this is your selected item
    }
    public void onNothingSelected(AdapterView<?> parent) 
    {

    }           
});
like image 119
Rahul Kumar Avatar answered Dec 04 '22 21:12

Rahul Kumar


Anyone looking For kotlin you can do like this:

spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
        override fun onNothingSelected(p0: AdapterView<*>?) {
        }

        override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long){
       }
    }
like image 26
Hamza Maqsood Avatar answered Dec 04 '22 22:12

Hamza Maqsood