I am trying to discriminate the selected item of a Spinner by its (multilanguage) text.
Here is my default strings.xml content:
<string-array name="spinner_items">
<item>length</item>
<item>weight</item>
<item>temperature</item>
</string-array>
And this is another strings.xml (Italian language) content:
<string-array name="spinner_items">
<item>lunghezza</item>
<item>peso</item>
<item>temperatura</item>
</string-array>
I set up my Spinner items in this way:
val items = resources.getStringArray(R.array.spinner_items)
spinner.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, items)
And then I add the item selected listener:
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
when(spinner.getItemAtPosition(position).toString()) {
"length" -> actionLength()
"lunghezza" -> actionLength()
"weight" -> actionWeight()
"peso" -> actionWeight()
"temperature" -> actionTemperature()
"temperatura" -> actionTemperature()
}
}
override fun onNothingSelected(parent: AdapterView<*>) {}
}
Everything works fine but the problem is that everytime I add a new language locale, I have to remember to add the specific string translation inside the when block. Is there a more "dynamic" way to do this?
I had the same problem in the past and here is how I solved it. Edit your strings.xml files by adding a string resource name for each items in your array, for example:
Default strings.xml
<string name="length">length</string>
<string name="weight">weight</string>
<string name="temperature">temperature</string>
<string-array name="spinner_items">
<item>@string/length</item>
<item>@string/weight</item>
<item>@string/temperature</item>
</string-array>
Italian strings.xml
<string name="length">lunghezza</string>
<string name="weight">peso</string>
<string name="temperature">temperatura</string>
<string-array name="spinner_items">
<item>@string/length</item>
<item>@string/weight</item>
<item>@string/temperature</item>
</string-array>
So in your code, you'll have:
when(spinner.getItemAtPosition(position).toString()) {
getString(R.string.length) -> actionLength()
getString(R.string.weight) -> actionWeight()
getString(R.string.temperature) -> actionTemperature()
}
I hope I was helpful!