android - 如何将视图模型变量与自定义类类型绑定
问题描述
什么有效?
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 类:
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);
}
我的活动:
@BindingAdapter({"items"})
public static void myMethod(View view, String[] feeds) {
// Do somthing
}
我想改变什么?
我想将 String[] 更改为List<Feed>
并且未达到 myMethod。
我的饲料类:
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 成员,但他当然会包含更多。
解决方案
在视图模型中更改如下
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);
}
//为提要列表实时数据创建getter和setter。
现在在 xml
app:items="@{viewModel.feedListLivedata }"
推荐阅读
- decision-tree - 根据预期效用选择操作
- javascript - 从统一 webGL 向嵌入它的 vue 页面发送消息
- javascript - 如何编写我自己的车把助手并在 patternlab-node 中使用它?
- c - 二叉搜索树,Valgrind 条件跳转或移动取决于未初始化的值
- visual-studio-code - 如何在视觉工作室代码(mac)中向上/向下移动多行?
- python - 如何选择 NumPy 数组中的所有非黑色像素?
- go - bufio.NewReader.ReadString() 中没有缓冲区大小限制?
- python - 创建窗口后在后台运行代码
- docker - sql developer中的imariadb,自动提交保持“真实”
- laravel - 具有多个房间的酒店预订系统的 Laravel 查询范围编辑方法