In many cases, Google is designedAndroidFollowed by a large numberMVC ArchitectureMethod To Make The Write PublicCode, Artist and specific logic developers are independent. How to format strings in the resource file values/strings. xml of Android? Here, android123 provides a simple example and what will be used in the end.
- <? XML version = "1.0" encoding = "UTF-8"?>
- <Resources>
- <String name = "app_name"> http://www.my400800.cn </string>
- <String name = "hello"> 400 phone number </string>
- </Resources>
Copy code
The above is a simple string resource file, not formatted, because it is relatively simple and straightforward to describe the meaning, when we design a file similar to delete XXX file? You may need to dynamically obtain the xxx name in Java, so you can easily use formatting to define resources, you don't need to splice a bunch of strings or use stringbuffer to append one by one. Let's look at the example.
- <String name = "alert"> Delete % 1 $ s file </string>
Copy code
Here % 1 $ s indicates that this is a string type. If it is an integer type, it can be written as % 1 $ D. It is a formatted string function similar to printf, of course, if there are multiple contents to be formatted, then the second one can be written as % 2 $ s or % 2 $ D. How can this be called in Java? See the following example:
Example 1: integer
- <String name = "alert"> I am % 1 $ D years old </string>
Copy code
The definition is as follows:
Of course, we should avoid unexpected situations, such as a string type such as secret. Note that the above is % 1 $ d rather than % 1 $ s, so the default standard is merged
- Int Nage = 23;
- String sageformat = getresources (). getstring (R. String. Alert );
- String sfinalage = string. Format (sageformat, Nage );
Copy code
After the execution is complete, it will constitute the I am 23 years old, isn't it very convenient? Of course, let's look at the situation of the string below.
Example 2: string type
- String sname = "cwj"
- String scity = "Shanghai"
Copy code
Resource is defined
- <String name = "alert2"> my name is % 1 $ S, I am form % 2 $ S </string>
Copy code
In Java, you only need
- String sinfoformat = getresources (). getstring (R. String. alert2 );
- String sfinalinfo = string. Format (sinfoformat, sname, scity );
Copy code
We can see that the entire definition is similar to the MFC cstring: format or the nslog in Mac OS, but you need to display the numbers marked with parameters similar to that shown in C, for example, % 1 or % N. Here, the number indicates the nth parameter. The final sfinalinfo displayed by the bank is