The replacement method in Android String.xml _android

Source: Internet
Author: User

This example describes the replacement method in the Android String.xml. Share to everyone for your reference, specific as follows:

In the development of Android, often meet a sentence, such as "I am 23 years old"; This 23 needs to be generated in the program, but there is a problem, this complete sentence is a textview, rather than three textview mosaic, It is written in a string.xml file, and can be implemented with string concatenation, but is especially troublesome;

Today encountered a good way, in the string.xml, not only can you set the text format line, and so on, you can also set the text format similar to the variable;

1, integral type , such as "I am 23 years old", this 23 is integral type. It can be written in String.xml, <string name= "old" > I%1$d this year </string>

In the program, use the

String Sageformat = Getresources (). getString (r.string.old);
String sfinalage = String.Format (Sageformat, 23);

Replace the%1$d with 23;

%1$d expression means the whole name= "old", the first integer substitution. If there are two integral types in a name that need to be replaced, the second one is:%2$d, and so on; Replace the string type shown in the program;

2, String type , such as "My name is Dick, I come from the capital of Beijing", where the "dick" and "capital of Beijing" need to be replaced.

It can be written in String.xml, <string name= "alert" > My name is%1 $ s, I am from%2$s</string>

In the program:

String SAGEFORMAT1 = Getresources (). getString (R.string.alert);
String SFinal1 = String.Format (SAGEFORMAT1, "Dick", "capital Beijing");

Here two strings need to be replaced, according to the order of the above program.

I hope this article will help you with the Android program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.