[英]Why isn't my LiveData<Drawable> being displayed as background?
我想通过LiveData对象动态更改按钮的背景。
我的ViewModel:
public class ViewModel {
public ViewModel(Context context) {
}
public LiveData<Drawable> getBackDrawable(){
MutableLiveData background = new MutableLiveData<>();
background.postValue(new ColorDrawable(Color.parseColor("#FF0000")));
return background;
}
}
我的Xml:
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<data>
<variable
name="ViewModel"
type="com.example.ckleineidam.testproject.ViewModel" />
</data>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/activation_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Test Button"
android:background="@{ViewModel.getBackDrawable}" />
</android.support.constraint.ConstraintLayout >
</layout>
为什么通过.postValue()
插入LiveData的可绘制对象不会显示为背景?
您正在将LiveData<Drawable>
分配给backgorund
property
因此无法实现所需的功能。
在“ Activity
Observe
Livedata
并将backgorund
应用于Button
。 并尝试yourBindingvar.executePendingBindings()
。 它可能会帮助您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.