Search code examples
androidandroid-databinding

Android databinding setText() over model binding


In my xml I have a line android:text='@{entry.printTitle}'

In my adapter I set entry: binding.setEntry(item); in bind() method.

For some occasions I want to set that field manually with binding.entryTitle.setText("some other title"), but it doesn't work. How can I set that field without affecting entry, which is immutable?


Solution

  • You can not override values of binding variables. If you want change dependent views, you have to change its variable value.

    You can take another variable for this purpose. And set value in this second variable when you want. Just make this second variable null when you have done.

    android:text='@{entry.fakeTitle ?? entry.printTitle}'
    

    Now when you want change title but not its variable then set value in fakeTitle.

    binding.getEntry().setFakeTitle("testing");
    

    When you have done make it null so text will be printTitle again.

    You have to use ObservableField<String> or LiveData, if you are changing value programmatically. If you are extending by BaseObservable then you have to make fakeTitle @Bindable and notify after changing.