Android string resource file format method usage example

Many times, we believe that Google abides by a large number of MVC architecture when designing Android, which can make developers who write public code, art and specific logic independent. How to format strings in the Android resource file values / strings.xml? Here's a simple example of Android 123 and where it may eventually be used.

The above is a simple string resource file without formatting, because it is relatively simple and directly describes the meaning. When we design a file similar to delete XXX file? We may need to dynamically obtain the name of XXX in Java, so it can be easily solved by using formatting when defining resources. We don't need a bunch of strings to splice or stringbuffers to append one by one. See the example < string name = "alert" > delete% 1 $s file < / String > here% 1 $s represents that this is a string type. If it is an integer type, it can be written as% 1 $d, Of course, if a formatted string function such as printf contains multiple contents that need to be formatted, the second one can be written as% 2 $s or% 2 $d. how to call it in Java? Take the following example:

Example 1: integer

< string name = "alert" > I am% 1 $d years old < / String > defines this. Of course, we prevent accidents. For example, a string type such as secret pops up. Note that% 1 $d above 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); After this, I am 23 years old will be formed. Isn't it convenient? Of course, let's take a look at the string

Example 2: string type

String sname = "cwj" string sicity = "Shanghai" resources are defined as < string name = "Alert2" > My name is% 1 $s, I am form% 2 $s < / String > then only string sinfoformat = getresources(). GetString (r.string. Alert2) is required in Java; String sFinalInfo=String.format(sInfoFormat,sName,sCity); We can see that the whole definition is similar to CString:: format in MFC or nslog in Mac OS, but the number indicating the parameter like that in C # should be displayed, such as% 1 or% N, where the number represents the nth parameter. My name is cwj, I am form Shanghai.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>