Home > Mobile >  Change Spinner Text content programmatically
Change Spinner Text content programmatically

Time:05-16

I have a spinner, and I want to find a way to change the dropdown for my spinner. I want to change my text content through code, but I'm not sure how to do that.

This is the structure of my Spinner:

val adapter: ArrayAdapter<String> = ArrayAdapter<String>(
                                        context,
                                        android.R.layout.simple_spinner_item, units1[i]
                                    )
                                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                                    val new_spin = Spinner(context)
                                    new_spin.setAdapter(adapter)

I want to change the text in my spinner to a different list (unit2).

CodePudding user response:

If you want to change the list your adapter is showing you can use clear and addAll to change the data.

For this case you will want to make sure not to pass the list in to the constructor of the adapter, otherwise calling clear or addAll will attempt to modify the original list. If the original list is immutable (listOf) it will throw an error, and if it is mutable (ArrayList) you may get unexpected behavior since it will modify the original source list.

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private val arr1 = listOf("1","2","3")
    private val arr2 = listOf("a","b","c")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // If you pass an array in here, calling things like "clear"
        // or "addAll" will modify the original list passed in. Passing in
        // nothing means the adapter will hold its own unique list...
        val adapter = ArrayAdapter<String>(this, R.layout.simple_spinner_item)

        // ...and you can initialize the adapter's list using addAll
        adapter.addAll(arr1)

        binding.mySpinner.adapter = adapter

        binding.changeSpinnerText.setOnClickListener {
            // to change what is shown, clear the adapter's list
            // and add the new values to show

            adapter.clear() // remove the existing values
            adapter.addAll(arr2) // add the new values
        }
    }
}
  • Related