Search code examples
android

How to set app: backgroundTint using Android Databinding LiveData


val inputUnderLineColor = MutableLiveData(R.color.red2)

app:backgroundTint="@{viewModel.inputUnderLineColor}"

I want to set the EditText UnderLine color value depending on the state, but I get the following error

Cannot find a setter for <android.widget.EditText app:backgroundTint> that accepts parameter type 'androidx.lifecycle.MutableLiveData<java.lang.Integer>'

How do you solve this ??


Solution

  • You can use it like below ContextCompat.getColor()

     <layout>
             <data>
                    <import type="android.support.v4.content.ContextCompat"/>
                    <variable name="viewModel" type="com.example.myapp.yourObject" />
                </data>
            ...
             <EditText 
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@{data.text}"
                    android:textColor="@{ContextCompat.getColor(context, viewModel.inputUnderLineColor)}" />
        </layout>
    

    1. Make sure to import ContextCompat as shown above.

    2. You can automagically 'context' as a method parameter for ContextCompat.getColor() because it will be automatically resolved to the view's context.