I have a spinner with some items (strings).
I want to add the selected items to a list. I read online that I should use the onItemSelectedListener
rather than the
I implemented like this. 1. Create Empty Mutable List 2. Set onItemSelectedListner on spinner 3. When user select item add that to mutable list
Check my this answer for more info. It will help you: Android Koltin pass spinner values to mutable list
instead of:
var spinnerArray = arrayOf("Dumbell", "Punching Bag", "Yoga Ball", "Skipping Rope")
try
var spinnerArray = mutableListOf<String>("Dumbell", "Punching Bag", "Yoga Ball", "Skipping Rope")
just had the same situation when I was trying to get a sqlite table´s $_ID and populate the spinner with them
Thanks this is helpful for me, Its working fine !
daysSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
}
string will not be able to check using '==' instead you need to use equals("string")
if (selectedItem.equals("Add new category")) {
// do your stuff
}
(in Kotlin)Use this code:
yourSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
}
Add extension function
fun Spinner.selected(action: () -> Unit) {
this.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
action()
}
}
}
simple use
spinner.selected {
// todo something
}