Android Tutorial 135
Using String Resources Programmatically
As shown earlier in this chapter, accessing string resources in code
is straightforward. There are two primary ways in which you can
access this string resource.
The following code accesses your application’s string resource
named hello, returning only the string. All HTML-style attributes
(bold, italic, and underlining) are stripped from the string.
String myStrHello =
getResources().getString(R.string.hello);
You can also access the string and preserve the formatting by using
this other method:
CharSequence myBoldStr =
getResources().getText(R.string.boldhello);
To load a format string, you need to make sure any format
variables are properly escaped.One way you can do this is by using
the TextUtils.htmlEncode() method:
import android.text.TextUtils;
...
String mySimpleWinString;
mySimpleWinString =
getResources().getString(R.string.winLose);
String escapedWin = TextUtils.htmlEncode(“Won”);
String resultText =
String.format(mySimpleWinString, 5, 5, escapedWin);
The resulting text in the resultText variable is
Score: 5 of 5! You Won.