Jetpack之DataBinding

对RecyclerView进行数据绑定

本质上就是在RecyclerView.Adapter中对每一个Item进行数据绑定,onCreateViewHolder中返回的是通过item的DataBinding的实例创建出来的组件对象;onBindViewHolder中对item的DataBinding实例设置了数据。

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {

    List<Idol> idols;

    public RecyclerViewAdapter(List<Idol> idols) {
        this.idols = idols;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemBinding binding=DataBindingUtil.inflate(LayoutInflater.from(parent.getContext())
            ,R.layout.item,parent,false);
        return new MyViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Idol idol=idols.get(position);
        holder.binding.setIdol(idol);
    }

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

    static class MyViewHolder extends RecyclerView.ViewHolder{

        private ItemBinding binding;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
        }

        public MyViewHolder(@NonNull ItemBinding binding) {
            super(binding.getRoot());
            this.binding=binding;
        }
    }
}

发表评论