You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android:能否仅通过资源文件合并两个字符串资源?

仅通过Android资源文件合并字符串资源的实现方法

可以实现,以下是两种无需编写Java/Kotlin代码的方案:

方案一:纯资源文件直接拼接(全Android版本支持)

如果不需要复用string_one的占位符逻辑,直接在新的字符串资源里写出合并后的内容并引用string_two即可:

<string name="string_one">Lets test the %s str</string>
<string name="string_two">Second</string>
<string name="combined_string">Lets test the @string/string_two str</string>

引用combined_string时,会直接显示Lets test the Second str。缺点是如果string_one的文本内容修改,需要手动同步combined_string的内容。

方案二:使用Data Binding(无需代码,需启用Data Binding)

如果想复用string_one的格式化逻辑,同时自动传入string_two作为参数,可以借助Data Binding实现:
确保项目启用Data Binding后,在布局文件的TextView中这样引用:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{@string/string_one(@string/string_two)}" />

这种方式下,string_one或string_two的内容修改时,显示的文本会自动同步更新。

注意:你之前尝试的${string_one} ${string_two}写法不符合Android资源文件的语法规范,无法生效。

内容的提问来源于stack exchange,提问作者A Damian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 02:12:48