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. Thank you.
@Override
public CategoryAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.common_circle_image, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull CategoryAdapter.MyViewHolder holder, final int position) {
holder.binding.img.setBackgroundResource(addAdapterData.get(position).getItemUrl());
holder.binding.txt.setText(addAdapterData.get(position).getItemName());
}
@Override
public int getItemCount() {
return addAdapterData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
CommonCircleImageBinding binding;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
binding = CommonCircleImageBinding.bind(itemView);
binding.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
commonItemClick.onItemClick(getAdapterPosition(),"");
}
});
}
}
Also, I want to know is it right to use R.layout.layout_name
and ViewBinding
in the same class.
What you need to do is pass the generated binding class object to the holder class constructor. In your example, You have
common_circle_image
XML file forRecyclerView
item and the generated class isCommonCircleImageBinding
so like this you use theonCreateViewHolder
to pass the generated binding class to theViewHolder
classand use the holder class like this so you can use these fields in
onBindViewHolder
You can create
CommonCircleImageBinding
directly inonCreateViewHolder
byCommonCircleImageBinding.inflate(LayoutInflater.from(parent.getContext()))
Then pass it to MyViewHolder
Here is full view binding recycler view code in java, you can do as like: