1

I need to create a Spinner(or exposed dropdown menu) where the user can select a duration, in this case an amount of days. Something like

one day
two days
three days

Later on I want to translate this app, so I can't use the displayed text in my code, e.g. something like

if(item.equals("one day"))

will fail for other languages than english.

So I want to have a "display value" (what's shown to the user, like "one day") and a technical id/key, something like "1DAY". How can that be done with Android resource files?

I finally want something like this:

<!-- give a technical key 1DAY/2DAYS/3DAYS etc to the items -->
<!-- this is just a mockup - how could something like this be really done? -->
<string-array name="duration">
    <item key="1DAY">@string/one_day</item>
    <item key="2DAYS">@string/two_days</item>
    <item key="3DAYS">@string/three_days</item>
    <!-- and so on -->
</string-array>

<!-- these strings could be translated -->
<string name="one_day">one day</string>
<string name="two_days">two days</string>
<string name="three_days">three days</string>
stefan.at.kotlin
  • 15,347
  • 38
  • 147
  • 270

2 Answers2

1

if(item.equals(getResources().getString(R.string.one_day)))

This will retrieve the correct string value from the correct language.

See this post for reference.

Daniel
  • 400
  • 1
  • 2
  • 12
0

Another option is to use the attribute tag. Tag save a key on your view, for example, you can create an enum like this:

enum class Days {
  ONE,
  TWO,
  THREE
}

And map your tag:

fun map(days: Days): Int =
    when(days) {
      ONE -> R.string.one
      TWO -> R.string.two
      else -> R.string.x
    }

So, the data to pass the view is:

val exampleDays = Days.ONE
val textId = map(exampleDays)

your_view.text = getString(textId)
your_view.tag = exampleDays

To recover the value, only fetch the tag:

val tag = your_view.tag as Days // cast in Kotlin
if (tag == Days.ONE) 

With this approach avoid duplicate strings and is a good way to work with clean architecture.

Manuel Mato
  • 771
  • 4
  • 10