Skip to content

Instantly share code, notes, and snippets.

@wongcain
Last active February 13, 2018 01:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wongcain/cad81f0610b9091f80b2762ab50d7bb0 to your computer and use it in GitHub Desktop.
Save wongcain/cad81f0610b9091f80b2762ab50d7bb0 to your computer and use it in GitHub Desktop.
RecyclerView Binding
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<import type="me.tatarka.bindingcollectionadapter2.LayoutManagers"/>
<variable name="vm" type="com.example.MyViewModel"/>
</data>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:itemBinding="@{vm.itemBinding}"
app:items="@{vm.items}"
app:layoutManager ="@{LayoutManagers.linear()}" />
package com.example.cain.mvvmexample;
import android.arch.lifecycle.ViewModel;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import me.tatarka.bindingcollectionadapter2.collections.DiffObservableList;
// See https://github.com/evant/binding-collection-adapter
public class MyViewModel extends ViewModel {
public DiffObservableList<Item> items
= new DiffObservableList<>(new DiffObservableList.Callback<Item>(){
@Override
public boolean areItemsTheSame(Item oldItem, Item newItem) {
return oldItem.equals(newItem);
}
@Override
public boolean areContentsTheSame(Item oldItem, Item newItem) {
return oldItem.equals(newItem);
}
});
public OnItemBind<Item> itemBinding = new OnItemBind<>() {
@Override
public void onItemBind(ItemBinding itemBinding, int position, Item item) {
itemBinding.set(BR.item, (position % 2 == 0)
? R.layout.even_item_layout : R.layout.odd_item_layout);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment