Adapter.getItemViewType(),配合 Adapter.getViewTypeCount() 使用,是用来实现在一个ListView上呈现不同的item样式。笔者之前在项目中使用该功能,却发现ListView一直无法刷新,也就是调用BaseAdapter.notifyDataSetChanged()无效:原因在于我的代码如下:
public static final int VIEW_TYPE1 = 1;
public static final int VIEW_TYPE2 = 2;
public static final int VIEW_TYPE3 = 3;
@Override
public int getItemViewType(int position) {
switch(position){
case 1:
return VIEW_TYPE1 ;
case 2:
return VIEW_TYPE2 ;
case 3:
return VIEW_TYPE3 ;
default:
return 1;
}
}
@Override
public int getViewTypeCount() {
return 3;
}
之后经过指点,才知道,getItemViewType()的返回值必须在 0 至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);
把代码代为:
public static final int VIEW_TYPE1 = 0;
public static final int VIEW_TYPE2 = 1;
public static final int VIEW_TYPE3 = 2;
@Override
public int getItemViewType(int position) {
switch(position){
case 1:
return VIEW_TYPE1 ;
case 2:
return VIEW_TYPE2 ;
case 3:
return VIEW_TYPE3 ;
default:
return 1;
}
}
@Override
public int getViewTypeCount() {
return 3;
}
这样就可以正常刷新了!