动态字符串使用String.xml?字符串、动态、xml、String

2023-09-12 01:23:49 作者:久了就旧了

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

例如:

  

一些字符串 PLACEHOLDER1 一些字符串

解决方案

格式和样式

是的,看到String资源:格式化和样式

  

如果你需要使用格式化你的字符串的String.Format(字符串,对象...),那么你可以把你的格式参数的字符串资源这样做。例如,用下面的资源:

 <字符串名称=welcome_messages>您好,%1 $ S!你有2%$ D新消息< /字符串>
 

在这个例子中,格式字符串有两个参数:%1 $ s是一个字符串,%2 $ d是一个十进制数。

:您可以从您的应用程序像这样格式化字符串参数

 资源资源= getResources();
字符串文本=的String.Format(res.getString(R.string.welcome_messages)
    用户名,mailCount);
 
字符串创建XML文档

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

 字符串文本= res.getString(R.string.welcome_messages,用户名,mailCount);
 

复数

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

 <复数名=welcome_messages>
    <项目数量=一>您好,%1 $ S!你有一个新的消息< /项目>
    <项目数量=其他>您好,%1 $ S!你有2%$ D新消息< /项目>
< /复数>
 

第一mailCount param用于决定使用(单个或多个)的格式,其他PARAMS是你的替换:

 资源资源= getResources();
字符串文本= res.getQuantityString(R.plurals.welcome_messages,
     mailCount,用户名,mailCount);
 

请参阅字符串资源:复数的更多细节。

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

Example:

some string PLACEHOLDER1 some more string

解决方案

Formatting and Styling

Yes, see the following from String Resources: Formatting and Styling

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>

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);

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>

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.