Android Kotlin onItemSelectedListener for spinner not working

后端 未结 6 1135
盖世英雄少女心
盖世英雄少女心 2021-02-03 18:12

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 onItemSelectedListenerrather than the

相关标签:
6条回答
  • 2021-02-03 18:19

    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

    0 讨论(0)
  • 2021-02-03 18:31

    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

    0 讨论(0)
  • 2021-02-03 18:34

    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) {
    
                }
    
            }
    
    0 讨论(0)
  • 2021-02-03 18:34

    string will not be able to check using '==' instead you need to use equals("string")

    if (selectedItem.equals("Add new category")) {
                // do your stuff
            }
    
    0 讨论(0)
  • 2021-02-03 18:37

    (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) {
    
            }
    
        }
    
    0 讨论(0)
  • 2021-02-03 18:37

    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
    }
    
    0 讨论(0)
提交回复
热议问题