Binding android data to android: background attribute using string color code

I have a color code saved as a string in a data object with a name beanas shown below:

public class SpaceBean extends BaseObservable {
    private String selectedThemeColor;

    @Nullable
    @Bindable
    public String getSelectedThemeColor() {
        return selectedThemeColor;
    }

    public void setSelectedThemeColor(String selectedThemeColor) {
        this.selectedThemeColor = selectedThemeColor;
        notifyPropertyChanged(BR.selectedThemeColor);
    }
}

I would like to use a data binding expression in a linear layout attribute android:background, for example:

<LinearLayout
        android:id="@+id/ll_space_detail_overlay"
        android:layout_width="match_parent"
        android:layout_height="144dp"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="@dimen/common_margin"
        android:layout_marginEnd="@dimen/common_margin"
        android:layout_marginStart="@dimen/common_margin"
        android:background="@{bean.selectedThemeColor}"
        android:clickable="true"
        android:orientation="vertical"
        android:padding="@dimen/common_padding"
        android:visibility="visible">

But it does not compile with an error:

Error: (80, 35) Cannot find the installer for the attribute 'android: background' with the parameter type java.lang.String on android.widget.LinearLayout.

+4
source share
1 answer

The reason for the lack of a method such as View.setBackground ("# f0f")!

Drawable ARGB SpaceBean.getSelectedThemeColor().

:

public class SpaceBean extends BaseObservable {
    private String selectedThemeColor;

    @Nullable
    @Bindable
    public Drawable getSelectedThemeColor() {
        return new ColorDrawable(Color.parseColor(selectedThemeColor));
    }

    public void setSelectedThemeColor(String selectedThemeColor) {
        this.selectedThemeColor = selectedThemeColor;
        notifyPropertyChanged(BR.selectedThemeColor);
    }
}
+3

All Articles