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

例子:

PLACEHOLDER1一些字符串


当前回答

但是,你也应该阅读Elias Mårtenson关于Android复数处理“零”的回答。对某些值(如“零”)的解释存在问题。

其他回答

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

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

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

<TextView android:text="@string/song_number_and_title"/>

如果你使用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))  

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

补充回答

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

它们被称为格式说明符。在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 lot of ways that you can format things (see the documentation). Here are some common ones: s string d decimal integer f floating point number

例子

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

我妹妹玛丽12岁了。

string.xml

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

MyActivity.java

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

笔记

I could use getString because 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$s multiple 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

Kotlin版本的公认答案…

val res = resources
val text = String.format(res.getString(R.string.welcome_messages), username, mailCount)

当你想使用实际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>

这对跨资源文件不起作用,即变量必须复制到每个需要它们的XML文件中。

你可以使用MessageFormat:

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

在Java代码中:

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

火力等级1:

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