How to databind livedata object (android)

感情迁移 提交于 2021-02-08 09:56:50

问题


Today I've some question about mvvm and databinding on android,

I'm trying to bind object properties on view.

I've an Object (Model) with some properties, by example :

public String name;
public String title;
public int value;

I've a ViewModel with livedata like this :

MutableLiveData<Object> _obj = new MutableLiveData<>();
public LiveData<Object> obj = _obj;

And, at last, I've a view like this :

<layout>
    <data>
        <variable
            name="viewModel">
            type="com.sample.app.viewmodels.MainViewModel" />
    </data>
    <LinearLayout
        ... >
        <TextView
            android:text:="@{viewModel.obj.name}"
            .../>
    </LinearLayout>
</layout>

I saw that we can do that in a video from "Android Developers" about "LiveData" : https://youtu.be/OMcDk2_4LSk?t=102

She says that its possible in Android studio on 3.1+ versions. But this is not working for me.


回答1:


For this to work, your model class must extend BaseObservable class from databinding library. And you have to call notifyChange() on each setter method like this:

public class Object extends BaseObservable {
    public String name;
    public String title;
    public int value;

    public void setName(String name) {
        this.name = name;
        notifyChange();
    }

    public void setTitle(String title) {
        this.title = title;
        notifyChange();
    }

    public void setValue(int value) {
        this.value = value;
        notifyChange();
    }
}


来源:https://stackoverflow.com/questions/56908707/how-to-databind-livedata-object-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!