另一种颜色是卡视图中的绑定颜色



您好,我正在尝试在CardView上设置app:cardBackgroundColor红色,为此我有以下代码:

    <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">

在视图模型中,我有以下代码:

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

为了更改颜色,我有以下代码:

  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);
                }
            }
        });

这个"工作"因为观察者将值更改为 R.color.red 在视图中更改了颜色,但新颜色是深蓝色而不是红色。

我正在尝试直接在布局中设置颜色,这项工作和颜色是红色的,但使用 ViewModel 则没有。

知道吗?

谢谢

当您直接传递 registerViewModel.passwordCvColor.setValue(R.color.red); id 时,颜色将是 R 文件中对颜色资源的引用,而不是颜色本身,类似于 0x7f010000,这几乎不是您想要的颜色。

应调用一个方法来使用此 id 获取资源。在旧版本中,您可以使用getResources().getColor()但是由于现在已弃用,因此您应该使用ContextCompat.getColor()

代码将如下所示:

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

最新更新