Search code examples
androidspinnerandroid-spinnerkotlin-android-extensions

How to change values of variable using Spinner?


How do I change the value of a variable using the spinner widget.

strings.xml

    <string name="selected_item">Selected item:</string>
    <string-array name="Languages">
        <item>English</item>
        <item>Latin</item>
        <item>French</item>
    </string-array>

mainactivity

        val spinner = findViewById<Spinner>(R.id.spinner)
        if (spinner != null) {
            val adapter = ArrayAdapter(
                this,
                android.R.layout.simple_spinner_item, languages
            )
            spinner.adapter = adapter

            spinner.onItemSelectedListener = object :
                AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>,
                    view: View, position: Int, id: Long
                ) {
                  
                   //what to do here?
                }

            }
        }

suppose I want to change the value of this variable

strokeManager.lang = "en"

Solution

  • So you will want to use the position to access it from the list that you used to populate the spinner.

    strokeManager.lang = languageMapToLangCode[languages.get(position)] 
    

    This should be defined in your class somewhere the spinner can access it

    val languageMapToLangCode: HashMap<String, String> = hashMapOf("French" to "fr", "Latin" to "ln", "English to "en")