您好,我尝试在app:cardBackgroundColor
的{{1}}中设置红色,为此,我有以下代码:
CardView
在ViewModel中,我有以下代码:
<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<>();
之所以如此“有效”,是因为观察者将值更改为R.color.red,视图中的颜色也随之更改,但是新颜色是深蓝色而不是红色。
我正在尝试直接在布局中设置颜色,这项工作和颜色是红色,但是使用ViewModel却没有。
有什么主意吗?
谢谢
答案 0 :(得分: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));