The Android string resource file format method USES the instance

  • 2020-05-19 05:44:31
  • OfStack

Most of the time we use Google to design Android in a large MVC way that allows us to write common code, artwork, and concrete logic developers independently. How do you implement formatting strings in values/ strings.xml resource files for Android? Here's a simple example of Android123 and where it might end up.


<?xml version="1.0" encoding="utf-8"?>
 <resources>
 <string name="app_name">cwj_Demo</string>
 <string name="hello">android Development of network </string>
</resources>

The above is a simple string resource file, no formatting is used, because it describes the meaning directly. When we design a file like Delete xxx File? We may need to get the name of xxx dynamically in Java, so using formatting when defining a resource can be easily solved without the need for 1 heap of String to be splicing or StringBuffer to have 1 append
< string name="alert" > Delete %1$s File < /string > Here %1$s means that this is 1 string, if it is an integer type can be written as %1$d, similar to printf format string function, of course, if it contains more than one need to format content, then the second can be written as %2$s or %2$d, so how to call it in Java? Here's an example:

Example 1: integer type

< string name="alert" > I am %1$d years old < /string > It's defined like this
Of course, we don't want to have unexpected situations, such as secret, string, etc. Notice that %1$d is not %1$s, so the default standard is merged into
int nAge=23;
String sAgeFormat = getResources().getString(R.string.alert);
String sFinalAge = String.format(sAgeFormat, nAge);
When you're done, you have I am 23 years old.

Example 2: string type

String sName="cwj"
String sCity="Shanghai"
Resources are defined as < string name="alert2" > My name is %1$s , I am form %2$s < /string >
In Java, only
String sInfoFormat = getResources().getString(R.string.alert2);
String sFinalInfo=String.format(sInfoFormat, sName, sCity);
We see the whole thing, the whole definition of NSLog in CString::Format or Mac OS, but we need to display the Numbers that indicate the parameters like in C#, such as %1 or %n, where the Numbers represent the n number of the parameters. The final sFinalInfo display of the row is
My name is cwj, I am form Shanghai.


Related articles: