adapter 中使用 getItemViewType 遇到的问题

工作中遇到在adapter  中显示2种类型的样式,需要在adapter 种重写 getItemViewType,和  getViewTypeCount 这两个方法,之前在用的时候没有太注意,在重写getItemViewType 的时候对于不同的ViewType 返回 1和2 ,后来老是奔溃,进去看源码,源码对这个方法的注释为:

/**

 * Get the type of View that will be created by {@link #getView} for the specified item.
 * 
 * @param position The position of the item within the adapter's data set whose view type we
 *        want.
 * @return An integer representing the type of View. Two views should share the same type if one
 *         can be converted to the other in {@link #getView}. Note: Integers must be in the
 *         range 0 to {@link #getViewTypeCount} - 1. {@link #IGNORE_ITEM_VIEW_TYPE} can
 *         also be returned.
 * @see #IGNORE_ITEM_VIEW_TYPE
 */

这里明确指出 返回的值一定要从0 到 getViewTypeCount -1,可以看出,这个地方gitItemViewType 返回的值不是随便乱设置的。android 源码是这么用,


/**
 * @return A view from the ScrapViews collection. These are unordered.
 */
View getScrapView(int position) {
    final int whichScrap = mAdapter.getItemViewType(position);
    if (whichScrap < 0) { 
        return null;
    }
    if (mViewTypeCount == 1) {
        return retrieveFromScrap(mCurrentScrap, position);
    } else if (whichScrap < mScrapViews.length) {
        return retrieveFromScrap(mScrapViews[whichScrap], position);
    }
    return null;
}

这里是itemViewType() 是mScrapViews 中的index, 难怪当我们把  getItemViewType 设置成1,2 的时候,会出现indexOutIndexException 这个错误,对于mScrapViews  

从scrapView中获取相应类型的view,这个数组是在 RecycleBin中,这个RecycleBin 的主要功能是为了更方便的复用view,他有两个层级,分别是ActiveViews和ScrapViews。ActiveViews是当前展示在屏幕上的 layout,但是最终所有的views 都将降级为ScrapViews。 ScrapViews  是被回收掉的不在屏幕展示的view, 他为了避免adapter 重新创建view。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值