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);
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)
{
}
});
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){
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With