android Adapter.getItemViewType()使用不当会导致AdapterView无法刷新

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

这样就可以正常刷新了!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值