Data binding in RecyclerView Adapter

suggest change

It’s also possible to use data binding within your RecyclerView Adapter.

Data model

public class Item {
    private String name;

    public String getName() {
        return name;
    }
}

XML Layout

res/layout/list_item.xml generates ListItemBinding. The variable type has to be the full class name of Item.

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="item"
            type="com.example.Item" />
    </data>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{item.name}" />
</layout>

Adapter class

public class ListItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Activity host;
    private List<Item> items;

    public ListItemAdapter(Activity activity, List<Item> items) {
        this.host = activity;
        this.items = items;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ListItemBinding binding = DataBindingUtil.inflate(
                host.getLayoutInflater(), R.layout.list_item, parent, false);
        return new ItemViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        Item item = items.get(position);
        ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
        itemViewHolder.bindItem(item);
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    private static class ItemViewHolder extends RecyclerView.ViewHolder {
        ListItemBinding binding;

        ItemViewHolder(ListItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bindItem(Item item) {
            binding.setItem(item);
            binding.executePendingBindings();
        }
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents