Populate Spinner in Android from List of Strings

Viewed 2103

(If you believe this question is a duplicate, check that the other answers are all Java instead of Kotlin)

I produce a spinner in an Android app from this Kotlin code:

val cameraSpinner: Spinner = findViewById(R.id.cameras_spinner)

I want the spinner to be populated with this list of Strings called camOptions:

val camOptions = arrayOfNulls<String>(cameraList.size)
for (i in cameraList.indices) { camOptions[i] = cameraList[i].name }

I do so by creating this adapter:

ArrayAdapter.createFromResource(this, camOptions, android.R.layout.simple_spinner_item).also {
    adapter ->
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    cameraSpinner.adapter = adapter }

Yet Android Studio complains about "camOptions" as the second parameter to createFromResource():

(IDE ERROR) Type mismatch.  Required:Int  Found:Array<String?>

Instead of an actual list of text objects, the function wants an integer acting as a resource ID for some list of text objects. I see how that works in the Android documentation where the text is predefined (load up the values in XML, then call on that resource), but in my case my list of cameras gets generated at runtime so I don't have that luxury.

How do I get my list of Strings to populate the spinner?

1 Answers

Well, Android Studio complains because the method you are using, clearly states that it is using createFromResource which will load data from the Resource.

So, in order for you to load data not from the Resource. You can use this

val adapter: ArrayAdapter<String> = ArrayAdapter<String>(
     this,
     android.R.layout.simple_spinner_item, camOptions
)
Related