What's wrong with this format string?

感情迁移 提交于 2019-12-12 07:46:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!