您的位置:首页 > 其它

adapter 中使用 getItemViewType 遇到的问题

2016-09-20 16:35 489 查看
工作中遇到在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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: