簡體   English   中英

為什么我的LiveData不是 <Drawable> 被顯示為背景?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM