What's wrong with this format string?

2019-04-05 02:27发布

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?

5条回答
看我几分像从前
2楼-- · 2019-04-05 02:44

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.

查看更多
smile是对你的礼貌
3楼-- · 2019-04-05 02:49

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楼-- · 2019-04-05 03:00

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>
查看更多
欢心
5楼-- · 2019-04-05 03:00

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);
查看更多
Explosion°爆炸
6楼-- · 2019-04-05 03:07

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>
查看更多
登录 后发表回答