How to concatenate an invoked String from an xml file with a variable?

Asked

Viewed 174 times

0

In Android Studio, I’m trying to concatenate a String I saved in an xml file (strings.xml) with a float variable as follows:

gas.setText(String.format("%s %s", R.string.gasoline_mod, value));

The saved string is as follows:

<string name="gasoline_mod">Gasoline: $</string>

However, when testing the application, instead of appearing the saved string in the xml, an 11-digit integer appears, followed by the float variable which, it seems, was correctly invoked. Is there any other way to invoke String or am I missing the syntax?

1 answer

0


For the application to access the string value, use the following method:

String string = getString(R.string.hello);

That is, in your code, change the first parameter:

gas.setText(String.format("%s %s", getString(R.string.gasoline_mod), value));

NOTE: You say you want to concatenate with a variable float. I believe this is your variable value. If that’s right, yours String.format is wrong.

Following table of the Pattern:

+-------+---------------------------------------------------+
| Char  | Applies to                                        |
+-------+---------------------------------------------------+
| %s    | string                                            |
| %d    | inteiros: byte, short, int, long, biting          |
| %e    | ponto flutuante (float) mas no formato científico |
| %d    | ponto flutuante                                   |
+-------+---------------------------------------------------+

I mean, your final line should be something like this:

gas.setText(String.format("%s %d", getString(R.string.gasoline_mod), value));
  • Brother, I’d like to start by thanking you for your attention. I was able to make the code work, but I had to leave the float as %s because when I put it as %d it crashed. But thank you very much, you saved my life here.

  • Hello Thiago. Ok. No problem. Accept the question whether it helped you or vote positive.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.