为啥会出现这个BUG呢! 在我写代码的时候理论上是不会出现,为啥出现了。因为ListView里面本来我是写了三个类型的,结果删了一个位置从1开始的类型,就出现了这个BUG。记录下提个醒。
在使用getItemViewType()时,它的起始位置是从0开始的。并且getViewTypeCount()的值必需大于getItemViewType()。记住getItemViewType()的type是从0开始的。比如:你getViewTypeCount()里面返回的是2,然后你类型定义返回的1和2,而getItemViewType()里面是从0开始,这样getItemViewType()就大于了getViewTypeCount()就会出现数组越界的异常。所以getItemViewType()里面的最大值不能大于getViewTypeCount()里面的值。
Adapter源码里面的解释 :range 0 to {@link #getViewTypeCount} - 1
/**
* 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
*/
int getItemViewType(int position);
/**
* <p>
* Returns the number of types of Views that will be created by
* {@link #getView}. Each type represents a set of views that can be
* converted in {@link #getView}. If the adapter always returns the same
* type of View for all items, this method should return 1.
* </p>
* <p>
* This method will only be called when when the adapter is set on the
* the {@link AdapterView}.
* </p>
*
* @return The number of types of Views that will be created by this adapter
*/
int getViewTypeCount();
一开始出现这个异常让我纳闷了,原来是我删除了1的item类型,而我getViewTypeCount()返回的是3,getItemViewType()里面最大的类型也是3。忘了是从0开始计算的了,以前的知识好像又忘得差不多了。