Search code examples
androidandroid-drawableandroid-databinding

Databinding bind android resource to background


I want to have an EditText that change its background according to the fact that it is editable or not.

If the EditText is "editable", it will have the default EditText background drawable and if it's not, it will get a transparent background (to look like a simple textView).

I've done this :

android:background="@{viewModel.editable ? android.R.drawable.edit_text : android.R.color.transparent}"

And it does not throw any exception during compilation or execution but my EditText seems to have no background and nothing change when the variable "editable" is modified.

My variable editable is a bindable variable defined like this :

@Bindable
boolean editable;

public boolean isEditable() {
    return editable;
}

public void setEditable(boolean editable) {
    this.editable = editable;
    notifyPropertyChanged(BR.editable);
}

Does someone has any clue about giving drawable resource according to a boolean?


Solution

  • According to the Data Binding Library documentation in the Custom Conversions section, your ternary expression should use XML notation for resource constants, instead of Java notation:

    android:background="@{viewModel.editable ? @android:drawable/edit_text : @android:color/transparent}"