Android ListView addScrapView ArrayIndexOutOfBoundsException

使用ListView自定义Adapter时出现ArrayIndexOutOfBoundsException错误:

java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
    at android.widget.AbsListView$RecycleBin.addScrapView(AbsListView.java:5996)
    at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4554)
    at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:3874)
    at android.os.Handler.handleCallback(Handler.java:605)
    at android.os.Handler.dispatchMessage(Handler.java:92)

CustomAdapter 的 getViewTypeCount() 方法返回值为2,表示ListView中有两种不同的视图,getItemViewType() 的返回值分别为1或2,取决于item在ListView中的位置。getItemViewType() 的返回值应该是从下标0开始的,所以应该返回0或者1。

解决办法:

static final int COMMON_ITEM = 0;
static final int CLEAR_ITEM = 1;

@Override
public int getViewTypeCount() {
    return 2;
}

@Override
public int getItemViewType(int position) {
    if (position != historyKey.length) {
        return COMMON_ITEM;
    } else {
        return CLEAR_ITEM;
    }
}

将getItemViewType() 的返回值改为 0或者1,运行不报错了,问题解决啦!

最后总结一点是:Adapter的getViewTypeCount 方法和getItemViewType方法返回值之间存在一定的关系。如果getViewTypeCount 返回值为 3,那么getItemViewType方法的返回值应该是 0、1、2,不能超过2,否则会出现ArrayIndexOutOfBoundsException异常。

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/02/25/android-listview-addscrapview-arrayindexoutofboundsexception/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Android ListView addScrapView ArrayIndexOutOfBoundsException
使用ListView自定义Adapter时出现ArrayIndexOutOfBoundsException错误: java.lang.ArrayIndexOutOfBoundsException: length=2; index=2 at android.widge……
<<上一篇
下一篇>>
文章目录
关闭
目 录