Skip to content

Latest commit

 

History

History
37 lines (29 loc) · 1.25 KB

android-databinding-recyclerview.md

File metadata and controls

37 lines (29 loc) · 1.25 KB

title: Android: Databinding and RecyclerView tags: android,android-databinding,android-recyclerview

If you want to do databinding in a RecyclerView:

  1. Ensure the ViewHolder has a variable for the binding.
  2. Change onCreateViewHolder to inflate your binding and pass that to the ViewHolder to return
  3. Setup the bindings in onBindViewHolder

For example:

public class MyRecycler extends RecyclerView.Adapter<MyRecycler.ViewHolder>{

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ListitemBinding viewDataBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.listitem, parent, false);
        return new ViewHolder(viewDataBinding);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.binding.setYoyo("Position: " + position);
    }

    @Override
    public int getItemCount() {
        return 40;
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        private ListitemBinding binding;
        public ViewHolder(ListitemBinding itemView) {
            super(itemView.getRoot());
            binding = itemView;
        }
    }
}