Domanda

I define a String in my strings.xml file:

<string name="unformatted_string">Here\'s a song I\'ve created just for you\! {0}</string>

And then I fetch that string and using MessageFormat.format, I replace {0} with a URL:

String str = MessageFormat.format(getString(R.string.unformatted_string), url);

When I print str, I see this:

Heres a song Ive created just for you http://www.google.com

The MessageFormat documentation states that rules for quotes are somewhat confusing, and then goes on to provide only a single example that only uses double-quotes. From my reading of the documentation, it seems my single-quote woes could be solved by using ''':

<string name="unformatted_string">Here'''s a song I'''ve created just for you\! {0}</string>

But the Android Resource Packaging step throws an error because I have an apostrophe not preceded by a \.

My only requirement is that the string be defined in strings.xml (to support localization).

È stato utile?

Soluzione

The file is an android resoure file, which mandates that every apostrophe is escaped with a preceding backslah. And MessageFormat requires every apostrophe in the pattern to be doubled. So you need two escaped apostrophes:

<string name="unformatted_string">Here\'\'s a song I\'\'ve created just for you\! {0}</string>

Altri suggerimenti

In XML, you can use the entity &#39; for the apostrophe.

However, the android resource does some further processing after parsing the XML and requires that apostrophes to be escaped with a backslash - regardless of whether they are represented as a entity or placed directly in the markup. This has nothing to do with XML. See guidelines here. Yuck! XML already offer complete encoding for all possible characters, it is a shame that the android system decided to put this unnecessary layer this on top.

Finally, the formatting of a message for output requires that apostrophes be doubled because apostrophe is the escape character for Java MessageFormat.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top