2012-11-24 30 views
3

我在列表视图中使用复选框,并希望获取ListView中的选定项。问题是SparseBooleanArray.size()始终保持为0,即使在该复选框被选中在listView.I寻觅了很多,但问题仍然存在一样。这是我使用的代码:获取SparseBooleanArray.size()从ListView中获取检查项时始终为0

checked = lvShowContacts.getCheckedItemPositions(); 
if(checked != null) 
{ 
    for (int i=0; i<checked.size(); i++) { 
     if (checked.valueAt(i)) { 
      String item = lvShowContacts.getAdapter().getItem(
        checked.keyAt(i)).toString(); 
      Log.v("Message",item + " was selected"); 
     } 
    } 
    Log.v("Message","checked.size() is "+ checked.size()); 
    // else 
    //the item is not checked, do something else 
} 

我在这里总是让checked.size()0。请帮助me.Thanks提前。

+0

你用'lvShowContacts.setChoiceMode(CHOICE_MODE_MULTIPLE)'? – Sam

+0

是的,我已经用它 – user1726619

+0

你使用的是什么行布局?它是否实现可检查? – Sam

回答

0

如果要循环所选行

int len = listView.getCount(); 
SparseBooleanArray checked = listView.getCheckedItemPositions(); 
for (int i = 0; i < len; i++) 
if (checked.get(i)) {  
    /* do whatever you want with the checked item */ 
} 

你会发现这个答案在这个线程:How to get Selected items from Multi Select List View

0

对于我来说,checked.size()总是返回0和值出现首先达到12,但具有正确的键/值对。所以我只是使用ListView的getCount来获得迭代的限制,并在遇到IndexOutOfBoudsException时完成。丑陋地狱,但到目前为止它的工作。

SparseBooleanArray checked = this.list.getCheckedItemPositions(); 
      ArrayList<String> ids = new ArrayList<String>(); 

      try { 
       for (int i = 0; i < this.list.getCount(); i++){ 
        if (checked.valueAt(i)){       
         Object r = this.list.getItemAtPosition(checked.keyAt(i)); 
         ids.add(r.getId());     
        }    
       } 
      } catch (IndexOutOfBoundsException e) { 
       Log.e(TAG, e.getMessage(),e); 
      } 
0

您可以通过将sparsebooleanarray转换为toString,然后将其拆分到“,”来获取sparsebooleanarray的大小。但是让我告诉你,这不是一个非常值得信赖的方法,从目前为止我所知道的,起初它只获取检查项目,它存储:{0=true, 1=true, 2=true}但假设你以某种方式保存了它的状态(使用共享前缀等)和然后取消选中检查的项目,然后返回, {0=true, 1=true, 2=false},ie, this time the size of the array will be 3 even when true state is only carried by 2. 因此,即使在返回计数时依赖sparsebooleanarray的大小也要小心。

0

使用SparseBooleanArray一些提示:

让SBA是一个SparseBooleanArray对象。

sba.size()返回数组中的项目总数。 现在,该数组包含一个Integer值到位置的映射,在这种情况下,所选列表视图项的位置将映射到相应的布尔状态。 使用sba.keyAt(i)来查找布尔数组的整数值,然后使用sba.get(sba.keyAt(i))来查找映射到整数键的相应布尔值。

可以遍历这样的数组:

SparseBooleanArray sba= getListView().getCheckedItemPositions(); 
    for(int i=0;i<sba.size();i++){ 
     Log.i("SparseBoolaeanArray","Element "+sba.keyAt(i)+":status::"+sba.get(sba.keyAt(i)));