问题
I have a string like this:
<string name="q_title" formatted="false">Item %d of %d</string>
I'm using it in String.format like this:
String log = String.format(getString(R.string.q_title), 100, 500);
So far I've observed no problems with the output.
However, code inspection in Android Studio gives me:
Format string 'q_title' is not a valid format string so it should not be passed to String.format
Why?
回答1:
Your string should be
<string name="q_title" formatted="false">Item %1$d of %2$d</string>
And code
String log = getString(R.string.q_title, 100, 500);
When you have multiple arguments you need to mark them with 1$, 2$... n$. In arabian langs order is reversed, so they need to know how to change it correctly.
getString(id, args...) perform format in itself.
回答2:
For percent, the following worked for me.
<string name="score_percent">%s%%</string>
getString(R.string.score_percent,"20")
If you are dealing with integers replace s by d
<string name="score_percent">%d%%</string>
回答3:
For those still looking for this answer, as the link that Blackbelt posted implies, the correct format for the string would be:
<string name="q_title">Item %1$d of %2$d</string>
回答4:
Beware to escape all special characters
I had a problem with this string because I forgot to escape the percentage character " % " at the end .
<string name="market_variation_formatter">%s %</string>
The good escaped string was :
<string name="market_variation_formatter">%s \%</string>
回答5:
If you need to format your strings, then you can do so by putting your format arguments in the string resource, as demonstrated by the following example resource.
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. Then, format the string by calling getString(int, Object...). For example:
String text = getString(R.string.welcome_messages, username, mailCount);
来源:https://stackoverflow.com/questions/17502824/whats-wrong-with-this-format-string