Listener on a Spinner
Asked Answered
C

2

6

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);
Crippen answered 28/2, 2017 at 11:16 Comment(0)
Y
15

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

    }           
});
Yashmak answered 28/2, 2017 at 11:21 Comment(1)
thanks,,this works,,,but umm i intended to use this with a list view,,so when i press spinner it will get the value on spinner and use it as an sql query then populate the list view. The onItemSelectedListener works but i cant seem to populate my list view,,any ideas?Crippen
N
6

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){
       }
    }
Nippon answered 30/8, 2019 at 6:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.