Last active
March 1, 2016 05:37
-
-
Save martin-cotta/23fadc9e03d2ce380bf9 to your computer and use it in GitHub Desktop.
Data Bound RecyclerView Adapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Activity extends AppCompatActivity { | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
RecyclerView recyclerView = getRecyclerView(); | |
List<Item> items = getItems(); | |
recyclerView.setAdapter(new DataAdapter(items)); | |
} | |
static class Adapter extends DataBoundAdapter<Item, ItemBinding> { | |
public Adapter(List<Item> items) { | |
super(items, R.layout.item); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class DataBoundAdapter<M extends ViewModel, B extends ViewDataBinding> | |
extends RecyclerView.Adapter<DataBoundAdapter.ViewHolder<B>> { | |
private final List<M> viewModels; | |
private final int itemLayoutId; | |
public DataBoundAdapter(List<M> viewModels, int itemLayoutId) { | |
this.itemLayoutId = itemLayoutId; | |
this.viewModels = viewModels; | |
} | |
@Override | |
public ViewHolder<B> onCreateViewHolder(ViewGroup parent, int viewType) { | |
B binding = DataBindingUtil.inflate( | |
LayoutInflater.from(parent.getContext()), itemLayoutId, parent, false); | |
return new ViewHolder<>(binding); | |
} | |
@Override | |
public void onBindViewHolder(ViewHolder<B> holder, int position) { | |
ViewDataBinding binding = holder.getBinding(); | |
binding.setVariable(BR.model, viewModels.get(position)); | |
binding.executePendingBindings(); | |
} | |
@Override | |
public int getItemCount() { | |
return viewModels.size(); | |
} | |
static class ViewHolder<T extends ViewDataBinding> extends RecyclerView.ViewHolder { | |
private T binding; | |
public ViewHolder(T binding) { | |
super(binding.getRoot()); | |
this.binding = binding; | |
} | |
public T getBinding() { | |
return binding; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment