android中多选框bug之getCheckItemIds()

       之前做项目的时候发现了android中listview并不能保存状态,查资料了好久,最终自己写了一个adapter来解决的。

       但是当时并没有发现getCheckItemIds()这个函数也有bug,因为当时用android2.2做的,能够正常运行,但是过了半年,在android2.1上测试才发现,2.1中这个函数google写的有明显bug,选中在取消选中后,返回的long[]中还有,具体的错误分析网上有好多,这里不再多写,解决方法网上有自己写adapter的,还有修改performItemClick,setItemChecked这两个函数的,总之方法好多这里主要记一下我的解决方法,自认为是最简单的解决方法。

       我是在类中添加了一个方法叫getListCheckedItemIds(),用来代替listview中的getCheckItemIds方法,很简单:

protected long[] getListCheckedItemIds(){
		final long[] ids = new long[listView.getCount()];
		int checkedCount = 0;
		for(int i=0;i<listView.getCount();i++){
			if(listView.isItemChecked(i)){
				ids[checkedCount++] = i;
			}
		}
		if (checkedCount == listView.getCount()) {
            return ids;
        } else {
            final long[] result = new long[checkedCount];
            System.arraycopy(ids, 0, result, 0, checkedCount);

            return result;
        }
	}

       PS:android2.2中推荐使用的是getCheckedItemIds,而不是getCheckItemIds,这里不推荐使用这个方法,不仅仅是之间版本中没有这个函数会导致程序出错,而且这个函数要求必须有stable id,才能正常工作,简单的使用一下arrayadapter的时候是不能正常工作的。

你可能感兴趣的:(android,工作,ListView,Google,测试)