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 onItemClickListener
.
I implemented this but I don't know how to complete the step of adding it to the list.
class NewKitListActivity : AppCompatActivity() { var spinnerArray = arrayOf("Dumbell", "Punching Bag", "Yoga Ball", "Skipping Rope") //var spinnerArray = arrayOf(DataService.kitList) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_new_kit_list) val spinner = newKitItemSpinner val spinnerArrayAdapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray) //selected item will look like a spinner set from XML spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner.adapter = spinnerArrayAdapter spinner.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { val selectedItem = parent.getItemAtPosition(position).toString() if (selectedItem == "Add new category") { // do your stuff } } // to close the onItemSelected override fun onNothingSelected(parent: AdapterView<*>) { } }}}
Thanks
Find the oldselected position in spinner and make it accesible and set it to -1 means internally its changing the selected position but user can't see. So when user selects same position as previously selected position in the spinner, it will get select without fail.
Spinners provide a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one. You can add a spinner to your layout with the Spinner object.
(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) { } }
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) { } }
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