Replacement of integer and string types in the android string. xml file

Source: Internet
Author: User

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.

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.