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

查看:80
本文介绍了在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 一些其他字符串

推荐答案

格式和样式

是的,请参见字符串资源:格式和样式设置

如果需要使用 String.format(String,Object ...)格式化字符串,则可以通过将format参数放入字符串资源中来进行格式化.例如,使用以下资源:

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天全站免登陆