简体   繁体   English

为什么我的LiveData不是 <Drawable> 被显示为背景?

[英]Why isn't my LiveData<Drawable> being displayed as background?

I want to change the background of a button dynamically via a LiveData object. 我想通过LiveData对象动态更改按钮的背景。

My ViewModel: 我的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;

    }
}

My Xml: 我的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>

Why won't the drawable that I inserted into the LiveData via .postValue() displayed as background? 为什么通过.postValue()插入LiveData的可绘制对象不会显示为背景?

you are assigning LiveData<Drawable> to backgorund property so you cannot achieve what you want. 您正在将LiveData<Drawable>分配给backgorund property因此无法实现所需的功能。

Observe Livedata in your Activity and apply backgorund to your Button . 在“ Activity Observe Livedata并将backgorund应用于Button and try yourBindingvar.executePendingBindings() . 并尝试yourBindingvar.executePendingBindings() it may Helps You. 它可能会帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM