Format Statement in a String Resource File

format statement in a string resource file

You do not need to use formatted="false" in your XML. You just need to use fully qualified string format markers - %[POSITION]$[TYPE] (where [POSITION] is the attribute position and [TYPE] is the variable type), rather than the short versions, for example %s or %d.

Quote from Android Docs: String Formatting and Styling:

<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 integer. You can format the string with
arguments from your application like this:

Resources res = getResources();
String text = res.getString(R.string.welcome_messages, username, mailCount);

format statement in string resource file usage

There is no need to use String.format. getString method already supports formatting.

So for instance:

 ((TextView) findViewById(R.id.text)).setText(getString(R.string.avg, "hr"));

Will results with

AVG hr

And

((TextView) findViewById(R.id.text)).setText(getString(R.string.avg, ""));

Will results with

AVG

Formatting string in xml resource file

You can use Html. When you load the string in the textview use:

yourTextView.setText(Html.fromHtml(context.getResources().getString(R.string.help_summary)));

And use html in the string, for example:

<string name="help_summary"><![CDATA[Clicking on button <span style="color:red">Summary</span> will result in <b>report</b>]]></string>

Replace part of String resource with format string

Let's suppose you have a resource

R.string.template_string as

On your return trip from studying Saturn's rings, you hear a distress signal that seems to be coming from the surface of Mars. It's strange because there hasn't been a colony there in years. Even stranger, it's calling you by name: \"Help me, %s, you're my only hope.\"

In code you can format this as

String username = "Bob"
String result = String.format(getResources().getString(R.string.template_string), username);

Warn:

You have incorrect template. Replace %1$s with %s 1$

How do I reference a color from a string resource to format my text?

You can't reference a color resource value from within your strings. You will have to keep using fgcolor="#FF00FFFF" or format your text at runtime.


Everything between <string name="contacts"> and </string> is treated as your text and it is not processed any further.

If you want to use your resource color, you will have to do this at runtime, by parsing / replacing parts in your String with the loaded value, or manually adding the right tags to it.



Related Topics



Leave a reply



Submit