Search code examples
androidandroid-databindingandroid-mvvm

How to bind a view model variable with custom class type


What works?

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 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:

    @BindingAdapter({"items"})
    public static void myMethod(View view, String[] feeds) {
        // Do somthing
    }

What i want to change?

I want to change String[] to List<Feed> and myMethod is not reached.

My Feed class:

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

For now, this class contains only one String members, but of course he will contain more.


Solution

  • 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.

    And now in xml

     app:items="@{viewModel.feedListLivedata }"