【问题标题】:Another color is binding color in Cardview?Cardview 中的另一种颜色是绑定颜色?
【发布时间】:2019-06-04 13:27:09
【问题描述】:

您好,我正在尝试在 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">

在 ViewModel 我有以下代码:

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 没有。

有什么想法吗?

谢谢

【问题讨论】:

  • 不知道是不是这样,暂时不能测试,但是有时候需要调用getColor()而不是直接传id
  • 如果你想创建一个问题,这项工作最终与ContextCompat.getColor(RegisterActivity.this, R.color.red) 合作。

标签: java android android-layout android-mvvm android-binder


【解决方案1】:

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

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

代码将如下所示:

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

【讨论】:

    最近更新 更多