As an exercise, I make a simple application for pizza ordering - the choice of size (affects the price) plus additional topping (also affects the price).

As a result, the order amount is calculated:

total.setText(getString(R.string.total_price_output) + String.format("%.02f", calculateTotal())); 

Here total_price_output is the phrase "Total Price: $" in strings.xml, a method calculateTotal () just calculates the total order value, taking into account the size and toppings.

Everything works, but Android Studio highlights this line with a yellow dash, i.e. The code does not comply with the rules of good tone and gives me this recommendation:

Do not concatenate text displayed with setText. Use resource string with placeholders.

How to proceed? Add a variable, assign it everything that now goes to setText () and then call setText () with this variable?

1 answer 1

The studio says that it is more correct to use placeholders in resources.

An example from official documentation (heading Formating strings).

line in resource file:

  <string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string> 

call in code:

 String text = getString(R.string.welcome_messages, username, mailCount); 

in place of %1$s in the resource row, the value of username substituted, in place of %2$d - mailCount . here, s in the placeholder means a string, and d is a number.

as a result, we get a string of the form: Hello, Petrov! You have 3 new messages

  • Thanks, then it really helped. However, yesterday it was necessary to add a third parameter to the line - and there was a problem with setText (): ru.stackoverflow.com/questions/844730/… - Vitaliy Tretyakov