我在项目中使用DataBindings和RecyclerView。 我有RecyclerView的基础适配器。看起来像这样
public abstract class BaseAdapter<T extends ViewDataBinding> extends RecyclerView.Adapter<BaseAdapter.ViewHolder> {
public BaseAdapter() {}
public class ViewHolder extends RecyclerView.ViewHolder {
public T binding;
public ViewHolder(View view) {
super(view);
binding = DataBindingUtil.bind(view);
}
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
... code ...
}
}
ViewHolder扩展类只有绑定字段类型不同。 在实现扩展的BaseAdapter类之后:
public class BaseAdapterExtended extends BaseAdapter<BaseAdapterExtendedBinding> {
public BaseAdapterExtended(ArrayList<ItemModel> itemModels) {
super();
mData = itemModels;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new ViewHolder(BaseAdapterExtendedBinding.inflate(inflater, parent, false).getRoot());
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
super.onBindViewHolder(holder, position);
}
@Override
protected View getItemRootView(ViewHolder holder) {
return holder.binding.item;
}
@Override
public int getItemCount() {
return mData.size();
}
}
我有下一个编译错误:
error: BaseAdapterExtended is not abstract and does not override abstract method onBindViewHolder(BaseAdapter.ViewHolder,int) in Adapter
似乎BaseAdapterExtended没有这种方法,但他存在。 如果我改变
public void onBindViewHolder(ViewHolder holder, int position)
到
public void onBindViewHolder(BaseAdapter.ViewHolder holder, int position)
预测编译正常,但类型绑定将是ViewDataBinding而不是BaseAdapterExtendedBinding。为什么会这样?有什么想法吗?
答案 0 :(得分:19)
在我的情况下,我忘记了参数化我的超类。创建类时,我还没有创建ViewHolder
,除了该方法的错误外,它非常宽松。即:
public class FooAdapter extends RecyclerView.Adapter {
不得不改为
public class FooAdapter extends RecyclerView.Adapter<FooAdapter.FooViewHolder> {
无论如何都需要这样做,但我得到的唯一编译错误是onBindViewHolder
。
答案 1 :(得分:7)
在这一行:
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
super.onBindViewHolder(holder, position);
}
将 ViewHolder 替换为 BaseAdapterExtended.ViewHolder
答案 2 :(得分:2)
我刚刚找到了这个奇怪问题的原因。这也发生在我的项目中,但仅适用于参数化的适配器,就像你的那样。所有其他适配器都看到了BindViewHolder()方法,而无需在类中显式指定ViewHolder。解决方案是使用任何随机参数类型对ViewHolder类进行参数化,这看起来像是一个错误。
public abstract class BaseAdapter<T extends ViewDataBinding> extends RecyclerView.Adapter<BaseAdapter.ViewHolder> {
public BaseAdapter() {}
public class ViewHolder<RandomTypeNotUsed> extends RecyclerView.ViewHolder {
public T binding;
public ViewHolder(View view) {
super(view);
binding = DataBindingUtil.bind(view);
}
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
... code ...
}
}
答案 3 :(得分:1)
对我来说很好! //就像是我的imageview
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int i) {
MyViewHolder myViewHolder1 = (MyViewHolder)viewHolder;
myViewHolder1.like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "yay" + i, Toast.LENGTH_SHORT ).show();
}
});
}