In Android development, I often encounter a sentence, for example, "I am 23 years old." This 23 must be generated in a program, but I have encountered a problem, this complete sentence is in a textview, instead of splicing the three textviews, and is a referenced string. written in an XML file. String concatenation is also possible, but it is especially troublesome;
Today, we have encountered a good method. In string. XML, we can not only set text format line breaks, but also text format similar to variables;
1. Integer. For example, "I am 23 years old this year". This 23 is an integer. This can be written in string. xml. <string name = "old"> I am % 1 $ d this year </string>
In the program, use
String sageformat = getresources (). getstring (R. String. Old );
String sfinalage = string. Format (sageformat, 23 );
Replace % 1 $ d with 23;
% 1 $ D represents the replacement of the first integer in the entire name = "old. If a name contains two integer values to be replaced, the second value is % 2 $ D, and so on. For details about replacement, see the string type below;
2. string type. For example, "My name is Li Si and I am from Beijing". Here, "Li Si" and "Beijing Capital" must be replaced.
This can be written in string. xml. <string name = "alert"> my name is % 1 $ s, and I am from % 2 $ S </string>
In the program:
String sageformat1 = getresources (). getstring (R. String. Alert );
String sfinal1 = string. Format (sageformat1, "Li Si", "capital Beijing ");
Here the two strings need to be replaced, which correspond in sequence according to the above program.