如何使用数据绑定将来自资源的字符串与 XML 中的动态变量结合起来?

新手上路,请多包涵

我有一个 TextView,它有一个硬编码的字符串,我有一个动态变量,我想把它放在这个字符串的末尾。这是我的代码:

 <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp">
    <TextView
        android:id="@+id/PeopleName"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/Generic_Text"+"@{ Profile.name }" />

</LinearLayout>

我遇到了 android:text="@string/Generic_Text"+"@{ Profile.name }" 的问题。 Generic_Text 声明“我的名字是”,然后 Profile.name 是动态的,并且从配置文件到配置文件显然会发生变化。我想要它,以便整个 TextView 输出是 My Name is {Profile.name} 。任何帮助都会很棒。

原文由 Ignacio Perez 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 713
2 个回答

你可以这样做:

 android:text= "@{String.format(@string/Generic_Text, Profile.name)}"

如果您对 Generic_Text 字符串使用字符串格式。前任。 %s 最后

原文由 C0D3LIC1OU5 发布,翻译遵循 CC BY-SA 3.0 许可协议

yourViewBinding.yourTextView.setText(this.yourViewBinding.getRoot().getResources().getString(R.string.your_string) + yourStringVariable);

原文由 Ashraf Amin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题