Why do we need to add @SuppressLint("SetTextI18n") annotation before concatenating strings in Android Studio
Asked Answered
G

1

16

I tried the following code for concatenation of 'number'(integer variable) and '$'(string) but I got a warning from android studio: "Do not concatenate text displayed with setText. Use resource string with placeholders." and suggested me to add "@SuppressLint("SetTextI18n")". After this the warning was gone.

What was the issue with concatenating the string. And why do we need to add

@SuppressLint("SetTextI18n")
fun displayPrice(number: Int){
    price_text_view.text= "$number$"
}
Gastight answered 7/6, 2020 at 13:8 Comment(0)
P
20

"I18" stands for "Internationalization". Android's localized resources mechanism allows you to support a variety of locales without having to modify your code. For example, here's how it could look if your application had to support multiple currencies:

In res/values-en_US/strings.xml:

<string name="price">%d$</string>

In res/values-en_UK/strings.xml:

<string name="price">%d£</string>

In res/values-de/strings.xml:

<string name="price">%d€</string>

Then your code would automatically pick up the correct version based on the device's locale:

fun displayPrice(number: Int) {
    price_text_view.text = resources.getString(R.string.price, number)
}

If your application only supports currencies with the $ symbol then it makes sense to hardcode it and use @SuppressLint("SetTextI18n") to silence the warning. Otherwise, consider using string resources.

Pentane answered 7/6, 2020 at 14:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.