我为RecycledView编写了适配器,它使用2种类型的项。因此,ViewHolder有3个类:基类和2个实现。

public abstract class AbstractCatalogItemViewHolder extends RecyclerView.ViewHolder {
    public WebImageView icon;
    ...
    public AbstractCatalogItemViewHolder(View itemView) {
        super(itemView);
    }
}

public  class CategoryViewHolder extends AbstractCatalogItemViewHolder {
    public CategoryViewHolder(View itemView) {
        super(itemView);
        icon = (WebImageView) itemView.findViewById(R.id.icon);
        ...
    }
}


问题是第二个图标指向对象(WebImageView),但是第一个图标是null。怎么可能?

@Override
public void onBindViewHolder(AbstractCatalogItemViewHolder abstractViewHolder,
                             final int position) {

    int type =  getItemViewType(position);

    WebImageView icon = abstractViewHolder.icon;
    WebImageView icon2 =  ((CategoryViewHolder)   abstractViewHolder).icon;
    ...
}




onCreateViewHolder:

  @Override
    public AbstractCatalogItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        int type =  getItemViewType(i);

        View v = inflater.inflate(
                type == TYPE_CATEGORY ?
                        R.layout.item_category :
                        R.layout.item_product,
                viewGroup, false);

        return type == TYPE_CATEGORY ? new CategoryViewHolder(v) : new ProductViewHolder(v);
    }

最佳答案

传递给onCreateViewHolder的int已经是itemType,请删除对getItemViewType内对onCreateViewHolder的调用。

09-11 18:15