问题
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