简体   繁体   English

RecyclerView 适配器类中 Android 视图绑定的正确方法是什么?

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

Here is the code I used in my RecycleView adapter class.这是我在RecycleView适配器类中使用的代码。 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.另外,我想知道在同一个类中使用R.layout.layout_nameViewBinding是否正确。

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 for RecyclerView item and the generated class is CommonCircleImageBinding so like this you use the onCreateViewHolder to pass the generated binding class to the ViewHolder class在您的示例中,您有用于RecyclerView项目的common_circle_image XML 文件,并且生成的类是CommonCircleImageBinding因此您使用onCreateViewHolder将生成的绑定类传递给ViewHolder

@NonNull
@Override
public CategoryAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    CommonCircleImageBinding itemBinding = CommonCircleImageBinding .inflate(LayoutInflater.from(parent.getContext()), parent, false);
    return new MyViewHolder(itemBinding);
}

and use the holder class like this so you can use these fields in onBindViewHolder并像这样使用 holder 类,以便您可以在onBindViewHolder使用这些字段

static class MyViewHolder extends RecyclerView.ViewHolder {
    private TextView txt;
    private ImageView img; 

    MyViewHolder(CommonCircleImageBinding itemBinding) {
        super(itemBinding.getRoot());
        img = itemBinding.img ;
        txt = itemBinding.txt ;
    }
}

Here is full view binding recycler view code in java, you can do as like:这是java中的完整视图绑定回收器视图代码,您可以这样做:

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<RecyclerViewListAdapter.ViewHolder> {
    public ArrayList<ModelObject> modelObjectArrayList;

    public RecyclerViewListAdapter(ArrayList<ModelObject> 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;
        }
    }
}

For the folks looking for a solution in Kotlin, here it is:对于在 Kotlin 中寻找解决方案的人来说,这里是:

It's a minimal example, where the adapter gets an array of Strings and displays each of the them in a layout called recyclerview_item in a TextView called itemTextView .这是一个最小的示例,其中适配器获取一个字符串数组并将它们中的每一个显示在名为itemTextView的 TextView 中名为recyclerview_item的布局中。

It's based on @SomeshKumar's answer and answers @Vijay Villiers question on how to get rid of the private TextView txt;它基于@SomeshKumar 的回答并回答了@Vijay Villiers 关于如何摆脱private TextView txt;

Edit: New Version: I noticed the generated ...Binding has a .bind() function, so let's use it.编辑:新版本:我注意到生成的 ...Binding 有一个 .bind() 函数,所以让我们使用它。 (I guess it might be less resource-heavy?) (我想它可能不那么占用资源?)

class SampleAdapter(private val context: Context, private val content: Array<String>) :
        RecyclerView.Adapter<SampleAdapter.CustomViewHolder>()
{
    class CustomViewHolder(view: View) : RecyclerView.ViewHolder(view)

    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int) =
            CustomViewHolder(
                    // Alternatively inflate like usual, if you don't need binding
                    RecyclerviewItemBinding
                            .inflate(LayoutInflater.from(context), viewGroup, false)
                            .root
            )

    override fun getItemCount() = content.size

    override fun onBindViewHolder(viewHolder: CustomViewHolder, position: Int)
    {
        RecyclerviewItemBinding.bind(viewHolder.itemView).apply{
            itemTextView.text = content[position]
            
        }
    }
} 

Edit: Old Version:编辑:旧版本:

class SampleAdapter(private val context: Context, private val content: Array<String>) :
        RecyclerView.Adapter<SampleAdapter.CustomViewHolder>()
{
    class CustomViewHolder(var viewBinding: RecyclerviewItemBinding) :
            RecyclerView.ViewHolder(viewBinding.root)

    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int) =
            CustomViewHolder(
                    RecyclerviewItemBinding
                            .inflate(LayoutInflater.from(context), viewGroup, false)
            )

    override fun getItemCount() = content.size

    override fun onBindViewHolder(viewHolder: CustomViewHolder, position: Int)
    {
        viewHolder.viewBinding.apply {
            itemTextView.text = content[position]
        }
    }
}

You can create CommonCircleImageBinding directly in onCreateViewHolder by CommonCircleImageBinding.inflate(LayoutInflater.from(parent.getContext()))您可以通过CommonCircleImageBinding.inflate(LayoutInflater.from(parent.getContext()))onCreateViewHolder直接创建CommonCircleImageBinding

Then pass it to MyViewHolder然后将其传递给 MyViewHolder

Here is full recycler view adapter class in java :这是 java 中的完整回收器视图适配器类:

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

    private List<Note> notes;
    private ItemNotesBinding notesBinding;

    public NotesAdapter(List<Note> notes) {
        this.notes = notes;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    
        notesBinding = ItemNotesBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new MyViewHolder(notesBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        Note note = notes.get(position);
        notesBinding.tvTitle.setText(note.getNote());
    }

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

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        ItemNotesBinding notesBinding;

        public MyViewHolder(@NonNull ItemNotesBinding binding) {
            super(binding.getRoot());
            notesBinding = binding;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 RecyclerView 适配器 class 中初始化正确的 TextView? - How to initialize right TextView in RecyclerView Adapter class? 传递给ArrayAdapter和RecyclerView适配器的视图和ViewGroup是什么? - What is the view and ViewGroup passed to ArrayAdapter and RecyclerView adapter? 如何在 RecyclerView 中使用 Android 视图绑定 - How to use Android View Binding with RecyclerView 有没有办法检查 Adapter 类之外的 RecyclerView 类是否为空? - Is there a way to check if the RecyclerView class is empty outside the Adapter class? 如何在扩展RecyclerView.Adapter的类中重新绑定视图 - How to rebind view in a class that extends RecyclerView.Adapter 如何使用Recycler View或RecyclerView适配器将XML解析为Java类 - How to parse an xml to java class with recycler view or in adapter of recyclerview 什么是 RecyclerView.Adapter<MyAdapter.MyViewHolder> 以及它与 Android 中的 RecyclerView.Adapter 有何不同? - What is RecyclerView.Adapter<MyAdapter.MyViewHolder> and how it is different from RecyclerView.Adapter in Android? 对于多个RecyclerView,适配器实现的良好而有效的方法是什么? - What is the good and efficient way of Adapter implementation for multiple RecyclerView? 在Android中实现RecyclerView的适配器 - Implementing an adapter for RecyclerView in Android Android RecyclerView适配器未初始化 - Android RecyclerView Adapter not initialize
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM