The substitution method in Android string.xml

  • 2020-12-20 03:44:34
  • OfStack

This article illustrates the substitution method in Android string.xml. To share for your reference, the details are as follows:

In the development of android, you often encounter a sentence such as "I am 23 years old"; This 23 needs to be generated in the program, but there is a problem. The complete 1 sentence is splited from 1 TextView instead of 3 textView, and it is written in the quoted ES9en.xml file. Using string concatenation can also be implemented, but it is particularly troublesome;

Today I have a good method. In ES13en. xml, you can not only set the format of text, such as line wrapping, but also the text format similar to variables.

1. An integer, such as "I am 23 years old". This 23 is an integer. In string.xml you could write, < string name="old" > I'm 1$d this year < /string >

In a program, use


String sAgeFormat = getResources().getString(R.string.old);
String sFinalAge = String.format(sAgeFormat, 23);

Replace %1$d with 23;

%1$d represents the substitution of the first integer throughout name= "old". If 1 name has two integers that need to be replaced, write the second as %2$d, and so on; For the specific procedure, see string type below;

2. string, such as "My name is Li 4 and I come from Beijing, the capital city"; Both "Li 4" and "Capital Beijing" need to be replaced.

In ES45en.xml you can write, < string name="alert" > My name is %1$s and I come from %2$s < /string >

In the program:


String sAgeFormat1 = getResources().getString(R.string.alert);
String sFinal1 = String.format(sAgeFormat1, " li 4"," The capital, Beijing ");

Here are the two string's that need to be replaced, in the order of the above program.

I hope this article is helpful for Android programming.


Related articles: