如何将视图模型变量与自定义类类型绑定 [英] How to bind a view model variable with custom class type
本文介绍了如何将视图模型变量与自定义类类型绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么有效?
XML:
name="viewModel"
type="com. . . . .MyViewModel" />
...
...
...
<android.support.v7.widget.RecyclerView
android:id="@+id/feeds_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
app:items="@{viewModel.feeds}"
/>
MyViewModel类:
MyViewModel class:
private String[] feeds;
...
...
public MyViewModel() {
String[] feeds = new String[] {"foo", "bar"};
setFeeds(feeds);
}
@Bindable
public String[] getFeeds() {
return feeds;
}
public void setFeeds( String[] feeds) {
this.feeds = feeds;
notifyPropertyChanged(BR.feeds);
}
MyActivity:
MyActivity:
@BindingAdapter({"items"})
public static void myMethod(View view, String[] feeds) {
// Do somthing
}
我要更改什么?
我想将String []更改为List<Feed>
并且未达到myMethod.
I want to change String[] to List<Feed>
and myMethod is not reached.
我的Feed类:
public class Feed {
private String name;
public Feed(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
目前,此类仅包含一个String成员,但是他当然将包含更多.
For now, this class contains only one String members, but of course he will contain more.
推荐答案
在viewmodel中像下面这样更改
Change this like below in viewmodel
private MutableLiveData<List<Feed>> feedListLivedata = new MutableLiveData<>();;
public MyViewModel() {
//create a list of feed here
setFeeds(feeds);
}
public void setFeeds( List<Feed> feeds) {
feedListLivedata .postValue(feeds);
}
//创建供稿列表实时数据的获取器和设置器.
//create getter and setter for feed list live data.
现在是xml
app:items="@{viewModel.feedListLivedata }"
这篇关于如何将视图模型变量与自定义类类型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文