DataBinding:根据条件选择字符串资源之一

DataBinding: Choose one of string resources depends on condition

我的数据对象中有一个布尔变量,当它为真时,我想显示来自资源的 1 个字符串,当它为假时,显示另一个。 我正在尝试这样做:

android:text="@{sendit.bccMode ? @string/sharebox.bcc_mode_on : @string/sharebox.bcc_mode_off}"

但是出现编译错误:

****/ data binding error ****msg:Could not find accessor java.lang.String.bcc_mode_on

我做错了什么?

Databinding 库在您使用 . (点)作为名称,将您的 strings.xml 文件更改为:

  <string name="sharebox_bcc_mode_on">BCC mode on</string>
  <string name="sharebox_bcc_mode_off">BCC mode off</string>

确切地说,您不必使用下划线代替点来重命名字符串,只需在使用此字符串时将点替换为下划线即可:

在文件中 strings.xml :

<string name="sharebox.bcc.mode.on">BCC mode on</string>
<string name="sharebox.bcc.mode.off">BCC mode off</string>

在数据绑定中(在activity.xml中):

android:text="@{sendit.bccMode ? @string/sharebox_bcc_mode_on : @string/sharebox_bcc_mode_off}"

所以你只需要转换'.'在数据绑定中使用此字符串时为“_”