是否可以在 strings.xml 中为运行时值设置占位符? [英] Is it possible to have placeholders in strings.xml for runtime values?

查看:21
本文介绍了是否可以在 strings.xml 中为运行时值设置占位符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 string.xml 中的字符串值中有占位符,可以在运行时赋值?

Is it possible to have placeholders in string values in string.xml that can be assigned values at run time?

示例:

一些字符串 PLACEHOLDER1 一些更多的字符串

some string PLACEHOLDER1 some more string

推荐答案

格式和样式

是的,请参阅字符串资源:格式和样式中的以下内容

如果您需要使用 String.format(String, Object...) 格式化您的字符串,那么您可以通过将您的格式参数放在字符串资源中来实现.例如,使用以下资源:

If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

在这个例子中,格式字符串有两个参数:%1$s 是一个字符串,%2$d 是一个十进制数.您可以使用应用程序中的参数来格式化字符串,如下所示:

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

基本用法

注意 getString 有一个使用字符串作为格式字符串的重载:

Basic Usage

Note that getString has an overload that uses the string as a format string:

String text = res.getString(R.string.welcome_messages, username, mailCount);

复数

如果您需要处理复数,请使用:

Plurals

If you need to handle plurals, use this:

<plurals name="welcome_messages">
    <item quantity="one">Hello, %1$s! You have a new message.</item>
    <item quantity="other">Hello, %1$s! You have %2$d new messages.</item>
</plurals>

第一个 mailCount 参数用于决定使用哪种格式(单数或复数),其他参数是你的替代:

The first mailCount param is used to decide which format to use (single or plural), the other params are your substitutions:

Resources res = getResources();
String text = res.getQuantityString(R.plurals.welcome_messages, mailCount, username, mailCount);

有关详细信息,请参阅字符串资源:复数.

See String Resources: Plurals for more details.

这篇关于是否可以在 strings.xml 中为运行时值设置占位符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆