Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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$"
}
like image 985
Keshav Kumar Avatar asked Jun 07 '20 13:06

Keshav Kumar


1 Answers

"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.

like image 59
Egor Avatar answered Nov 05 '22 08:11

Egor