是否可以在 Android 中将 String 动态添加到 String.xml?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3656371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:12:14  来源:igfitidea点击:

Is it possible dynamically to add String to String.xml in Android?

androidstringstring-formattingandroid-resources

提问by SoftReference

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

是否可以在字符串值中使用占位符,string.xml以便在运行时分配值?

Example:

例子:

some string PLACEHOLDER1some more string

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

回答by Megha Joshi - GoogleTV DevRel

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$sis a string and %2$dis 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);

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

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

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

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

Basic Usage

基本用法

Note that getStringhas an overload that uses the string as a format string:

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

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 mailCountparam is used to decide which format to use (single or plural), the other params are your substitutions:

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

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

See String Resources: Pluralsfor more details.

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

回答by Suragch

Supplemental Answer

补充答案

When I first saw %1$sand %2$din the accepted answer, it made no sense. Here is a little more explanation.

当我第一次看到%1$s%2$d在接受的答案中时,它没有任何意义。这里有更多的解释。

They are called format specifiers. In the xml string they are in the form of

它们被称为格式说明符。在 xml 字符串中,它们的形式为

%[parameter_index$][format_type] 
  • %: The percent sign marks the beginning of the format specifier.
  • parameter index: This is a number followed by a dollar sign. If you had three parameters that you wanted to insert into the string, then they would be called 1$, 2$, and 3$. The order you place them in the resource string doesn't matter, only the order that you supply the parameters.
  • format type: There are a lotof ways that you can format things (see the documentation). Here are some common ones:

    • sstring
    • ddecimal integer
    • ffloating point number
  • %:百分号标记格式说明符的开始。
  • 参数 index:这是一个数字,后跟一个美元符号。如果你有,你想插入串三个参数,那么他们将被称为1$2$3$。您在资源字符串中放置它们的顺序无关紧要,重要的是您提供参数的顺序。
  • 格式类型:有很多方法可以格式化事物(请参阅文档)。以下是一些常见的:

    • s细绳
    • d十进制整数
    • f浮点数

Example

例子

We will create the following formatted string where the gray parts are inserted programmatically.

我们将创建以下格式化字符串,其中灰色部分以编程方式插入。

My sister Maryis 12years old.

我妹妹Mary12岁。

string.xml

字符串.xml

<string name="my_xml_string">My sister %1$s is %2$d years old.</string>

MyActivity.java

我的活动.java

String myString = "Mary";
int myInt = 12;
String formatted = getString(R.string.my_xml_string, myString, myInt);

Notes

笔记

  • I could use getStringbecause I was in an Activity. You can use context.getResources().getString(...)if it is not available.
  • String.format()will also format a String.
  • The 1$and 2$terms don't need to be used in that order. That is, 2$can come before 1$. This is useful when internationalizing an app for languages that use a different word order.
  • You can use a format specifier like %1$smultiple times in the xml if you want to repeat it.
  • Use %%to get the actual %character.
  • For more details read the following helpful tutorial: Android SDK Quick Tip: Formatting Resource Strings
  • 我可以使用,getString因为我在一个活动中。context.getResources().getString(...)如果它不可用,您可以使用。
  • String.format()还将格式化一个字符串。
  • 1$2$术语并不需要按顺序使用做。也就是2$可以先来1$。这在针对使用不同词序的语言国际化应用程序时非常有用。
  • %1$s如果要重复,可以在 xml 中多次使用格式说明符。
  • 使用%%以获得实际%的性格。
  • 有关更多详细信息,请阅读以下有用的教程:Android SDK 快速提示:格式化资源字符串

回答by Oded Breiner

When you want to use a parameter from the actual strings.xml file without using any Java code:

当您想使用来自实际 strings.xml 文件的参数而不使用任何 Java 代码时:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE resources [
  <!ENTITY appname "WhereDat">
  <!ENTITY author "Oded">
]>

<resources>
    <string name="app_name">&appname;</string>
    <string name="description">The &appname; app was created by &author;</string>
</resources>

This does not work across resource files, i.e. variables must be copied into each XML file that needs them.

这不适用于资源文件,即必须将变量复制到需要它们的每个 XML 文件中。

回答by user3016503

Was looking for the same and finally found the following very simple solution. Best: it works out of the box.
1. alter your string ressource:

一直在寻找相同的东西,终于找到了以下非常简单的解决方案。最佳:它开箱即用。
1. 改变你的字符串资源:

<string name="welcome_messages">Hello, <xliff:g name="name">%s</xliff:g>! You have 
<xliff:g name="count">%d</xliff:g> new messages.</string>

2. use string substitution:

2. 使用字符串替换:

c.getString(R.string.welcome_messages,name,count);

c.getString(R.string.welcome_messages,name,count);

where c is the Context, nameis a string variable and countyour int variable

其中 c 是上下文,名称是字符串变量并计算您的 int 变量

You'll need to include

你需要包括

<resources xmlns:xliff="http://schemas.android.com/apk/res-auto">

in your res/strings.xml. Works for me. :)

在您的 res/strings.xml 中。为我工作。:)

回答by msbodw001

In Kotlin you just need to set your string value like this:

在 Kotlin 中,您只需要像这样设置字符串值:

<string name="song_number_and_title">"%1$d ~ %2$s"</string>

Create a text view on your layout:

在你的布局上创建一个文本视图:

<TextView android:id="@+id/song_number_and_title"/>

Then do this in your code if you using Anko:

如果您使用 Anko,则在您的代码中执行此操作:

val song = database.use { // get your song from the database }
song_number_and_title.setText(resources.getString(R.string.song_number_and_title, song.number, song.title))  

You might need to get your resources from the application context.

您可能需要从应用程序上下文中获取资源。

回答by JJD

However, you should also read Elias M?rtenson's answer on Android plurals treatment of “zero”. There is a problem with the interpretation of certain values such as "zero".

但是,您还应该阅读Elias M?rtensonAndroid 复数处理“零”的回答。某些值(例如“零”)的解释存在问题。

回答by Ahmad Aghazadeh

You can use MessageFormat:

您可以使用MessageFormat

<string name="customer_address">Wellcome: {0} {1}</string>

In Java code :

在 Java 代码中:

String text = MessageFormat(R.string.customer_address).format("Name","Family");

API level 1:

API 级别 1:

https://developer.android.com/reference/java/text/MessageFormat.html

https://developer.android.com/reference/java/text/MessageFormat.html

回答by Chanh

in res/values/string.xml

在 res/values/string.xml 中

<resources>
    <string name="app_name">Hello World</string>
    <string name="my_application">Application name: %s, package name: %s</string>
</resources>

in java code

在java代码中

String[] args = new String[2];
args[0] = context.getString(R.string.app_name);
args[1] = context.getPackageName();
String textMessage = context.getString(R.string.my_application,(Object[]) args);

回答by César Mu?oz

Yes! you can do so without writing any Java/Kotlin code, only XML by using this small library I created, which does so at buildtime, so your app won't be affected by it: https://github.com/LikeTheSalad/android-string-reference

是的!您可以在不编写任何 Java/Kotlin 代码的情况下这样做,只需使用我创建的这个小型库的 XML,它在构建时这样做,因此您的应用程序不会受到它的影响:https: //github.com/LikeTheSalad/android -字符串引用

Usage

用法

Your strings:

你的字符串:

<resources>
    <string name="app_name">My App Name</string>
    <string name="template_welcome_message">Welcome to ${app_name}</string>
</resources>

The generated string after building:

构建后生成的字符串:

<!--resolved.xml-->
<resources>
    <string name="welcome_message">Welcome to My App Name</string>
</resources>

回答by nyxee

A Direct Kotlin Solution to the problem:

问题的直接 Kotlin 解决方案:

strings.xml

字符串.xml

<string name="customer_message">Hello, %1$s!\nYou have %2$d Products in your cart.</string>

kotlinActivityORFragmentFile.kt:

kotlinActivityORFragmentFile.kt:

val username = "Andrew"
val products = 1000
val text: String = String.format(
      resources.getString(R.string.customer_message), username, products )