首页 > 解决方案 > 如何将视图模型变量与自定义类类型绑定

问题描述

什么有效?

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 成员,但他当然会包含更多。

标签: androidandroid-databindingandroid-mvvm

解决方案


在视图模型中更改如下

   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 }"

推荐阅读