DataBinding:如何创建具有相同模型和不同布局的 RecyclerView Adapter?

DataBinding: How to create RecyclerView Adapter with same model and different layout?

我对两种不同的项目布局使用相同的适配器。一种用于网格,一种用于线性显示。我将带有 itemLayout 的布局 ID 传递给适配器。但是,我无法正确添加数据绑定。你能帮帮我吗?

到目前为止,这是我的适配器工作:

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

    ArrayList<Oyuncu> oyuncuListesi;
    Context context;
    int itemLayout;

    public OyuncuAdapter(ArrayList<Oyuncu> oyuncuListesi, Context context, int itemLayout) {
        this.oyuncuListesi = oyuncuListesi;
        this.context=context;
        this.itemLayout = itemLayout;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {         
        View v = LayoutInflater.from(context).inflate(itemLayout, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Oyuncu oyuncu = oyuncuListesi.get(position);
        holder.binding.setVariable(BR.oyuncu, oyuncu);
        holder.binding.executePendingBindings();

    }

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

    public static class ViewHolder extends RecyclerView.ViewHolder{

        private ViewDataBinding binding;

        public ViewHolder(View itemView) {
            super(itemView);
            binding = DataBindingUtil.bind(itemView);

        }
    }
}

项目布局如下:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="oyuncu"
            type="com.figengungor.suits.model.Oyuncu" />

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical"
        android:padding="@dimen/itemPadding"
        tools:background="@color/darkgrey">

        <ImageView
            android:id="@+id/foto"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:gravity="center"
            android:scaleType="centerCrop"
            app:imageResource="@{oyuncu.foto}"
            tools:src="@drawable/gabrielmacht" />

        <TextView
            android:id="@+id/isim"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textColor="@android:color/white"
            android:text="@{oyuncu.isim}"
            tools:text="Gabriel Macht" />

    </LinearLayout>

</layout>

我得到的错误并没有多大帮助:

Caused by: java.lang.RuntimeException: view tag isn't correct on view:null

我的错。这部分工作完美。我的问题是扩展也使用 DataBinding 的 BaseActivity。崩溃与此有关。从我的 activity 中删除扩展 BaseActivity 后,它起作用了。但是,我打开了另一个与此相关的问题。如果你能看看那个,我将不胜感激。 DataBinding: How to use BaseActivity