Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataBinding: Choose one of string resources depends on condition

I have a boolean variable in my data-object, and want to show 1 string from resources when it is true, and another when it is false. I am trying to do it this way:

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

But getting an compilation error:

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

What do I am doing wrong?

like image 380
Viktor Sinelnikov Avatar asked May 09 '17 14:05

Viktor Sinelnikov


People also ask

Which is better Viewbinding and DataBinding?

The main advantages of viewbinding are speed and efficiency. It has a shorter build time because it avoids the overhead and performance issues associated with DataBinding due to annotation processors affecting DataBinding's build time.

When should I use DataBinding?

With data binding, a change to an element in a data set automatically updates in the bound data set. Data binding may be used for many reasons, such as to link an application's user interface (UI) and the data it displays, for data entry, reporting and in text box elements.


2 Answers

The Databinding library is lost when you use the . (dot) as a name, change your strings.xml file to this:

  <string name="sharebox_bcc_mode_on">BCC mode on</string>
  <string name="sharebox_bcc_mode_off">BCC mode off</string>
like image 50
Luiz Fernando Salvaterra Avatar answered Sep 19 '22 10:09

Luiz Fernando Salvaterra


To be exact, you don't have to rename your strings with an underscore in place of a dot, just replace dots by underscores when you USE this string :

in the file strings.xml :

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

in the databinding (in activity.xml) :

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

So you just have to convert '.' to '_' when you use this strings in databinding

like image 32
MarioR Avatar answered Sep 18 '22 10:09

MarioR