What is the right way of Android View Binding in the RecyclerView adapter class?

前端 未结 5 1494
[愿得一人]
[愿得一人] 2021-02-14 07:08

Here is the code I used in my RecycleView adapter class. I don\'t know this is the right way or not to use View Binding. If you have a better solution answer me. Th

5条回答
  •  爱一瞬间的悲伤
    2021-02-14 08:03

    Here is full view binding recycler view code in java, you can do as like:

    package com.jbws.myviewbindingdemo.adapter;
    
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    import androidx.annotation.NonNull;
    import androidx.recyclerview.widget.RecyclerView;
    
    import com.jbws.myviewbindingdemo.databinding.RowXmlViewBinding;
    import com.jbws.myviewbindingdemo.pojo.ModelObject;
    
    import java.util.ArrayList;
    
    public class RecyclerViewListAdapter extends RecyclerView.Adapter {
        public ArrayList modelObjectArrayList;
    
        public RecyclerViewListAdapter(ArrayList modelObjectArrayList) {
            this.modelObjectArrayList = modelObjectArrayList;
        }
    
        @NonNull
        @Override
        public RecyclerViewListAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ViewHolder(RowXmlViewBinding.inflate(LayoutInflater.from(parent.getContext()),
                    parent, false));
        }
    
        @Override
        public void onBindViewHolder(@NonNull RecyclerViewListAdapter.ViewHolder holder, final int position) {
            ModelObject modelObject = modelObjectArrayList.get(position);
            holder.rowXmlViewBinding.txtObjectName.setText(modelObject.getFullName());
            holder.rowXmlViewBinding.btnUpdateName.setOnClickListener(view -> {
             Log.i("LOG_TAG", "Full Name: " + modelObject.getFullName);
            });
        }
    
        @Override
        public int getItemCount() {
            return modelObjectArrayList == null ? 0 :
                    modelObjectArrayList.size();
        }
    
        public static class ViewHolder extends RecyclerView.ViewHolder {
            private RowXmlViewBinding rowXmlViewBinding;
    
            public ViewHolder(RowXmlViewBinding rowXmlViewBinding) {
                super(rowXmlViewBinding.getRoot());
                this.rowXmlViewBinding = rowXmlViewBinding;
            }
        }
    }
    

提交回复
热议问题