Android抽象类坏魔法nullpointer

时间:2015-04-23 15:58:47

标签: java android polymorphism

我为RecycledView编写了适配器,它使用了两种类型的项目。因此ViewHolder有三个类:基类和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;
    ...
}

enter image description here

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);
    }

1 个答案:

答案 0 :(得分:0)

传递到onCreateViewHolder的int已经是itemType,移除了对getItemViewTypeonCreateViewHolder的调用。