Search code examples
javaandroidandroid-layoutandroid-mvvmandroid-binder

Another color is binding color in Cardview?


Hello I am trying set a red color in app:cardBackgroundColor on a CardView for do this I have the following code:

    <android.support.v7.widget.CardView
                    android:id="@+id/cvPassword"
                    style="@style/card_view.with_elevation.edit_text"
           app:cardBackgroundColor="@{registerViewModel.passwordCvColor}"
                    android:layout_marginTop="24dp"
                    app:layout_constraintBottom_toTopOf="@id/checkBox"
                    app:layout_constraintEnd_toEndOf="@id/guidelineRegisterEnd"
                    app:layout_constraintStart_toStartOf="@id/guidelineRegisterStart"
                    app:layout_constraintTop_toBottomOf="@id/cvRepeatEmail">

In the ViewModel I have the following code:

public final MutableLiveData<Integer> passwordCvColor = new MutableLiveData<>();

And for change the color I have the following code:

  binding.setPasswordHandler(new Handler(){
            @Override
            public void onFocusLost() {
                String password = registerViewModel.email.getValue();
                if(password == null || password.isEmpty()){
                    registerViewModel.passwordCvColor.setValue(R.color.red);
                }else{
                    registerViewModel.passwordCvColor.setValue(null);
                }
            }
        });

This "work" because the observer changes the value to R.color.red the color is changed in the view, but the new color is dark blue instead of red.

I am trying to set directly the color in the layout, and this work and the color is red, but with the ViewModel doesn't.

Any idea?

Thanks


Solution

  • As you're passing directly the id in registerViewModel.passwordCvColor.setValue(R.color.red); the color will be the reference to the color resource in the R file and not the color itself, something like 0x7f010000 and that hardly will be the color you want.

    You should call a method to get the resource using this id instead. In the older versions you could use getResources().getColor() but as it is deprecated now you should use ContextCompat.getColor().

    The code will look like this:

    registerViewModel.passwordCvColor.setValue(ContextCompat.getColor(RegisterActivity.this, R.color.red));