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

时间:2016-10-16 20:06:09

标签: android android-recyclerview android-databinding

我对两个不同的项目布局使用相同的适配器。一个用于网格,一个用于线性显示。我将带有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

1 个答案:

答案 0 :(得分:0)

我的坏。这部分很完美。我的问题是扩展BaseActivity,它也使用DataBinding。崩溃与此有关。从我的活动中删除扩展BaseActivity后,它工作正常。但是,我打开了另一个问题。如果你能看一下,我会感激不尽。 DataBinding: How to use BaseActivity