2014-04-21 164 views
0

我在我的应用程序中使用了多选列表视图。具体来说就是simple_list_item_activated_1。选择/取消选择列表视图中的所有项目

我有一些代码,一个按钮,将选择所有的listview项目。我有一些逻辑说,如果所有的项目已被选中,则取消选择所有的项目。

当我第一次按下按钮时,它会按预期方式选择列表中的所有项目。当我再次按下按钮时,它会按预期取消选择所有项目。

这是我的问题: 当我第三次按下按钮“selectedCount”仍然等于“childCount”。所以显然我的代码永远不会进入If语句。

有人会知道为什么会发生这种情况吗?或者也许有更好的方式来做什么即时通讯试图实现?

int childCount = officerList.getChildCount(); 
    int selectedCount = officerList.getCheckedItemPositions().size(); 

      if(childCount != selectedCount){ 
       for (int i = 0; i < officerList.getChildCount(); i++) { 
        officerList.setItemChecked(i, true); 
       } 
      }else{ 
       for (int i = 0; i < officerList.getChildCount(); i++) { 
        officerList.setItemChecked(i, false); 
       } 
      } 
     } 

回答

0

我设法回答我自己的问题。使用getCheckItemPositions()。size()是实现我想要的不可靠方法。

这将返回所有项目的sparseBooleanArray()检查,所以它第一次正常工作,因为最初没有选择任何东西,所以它将返回0.然后,一旦选择了一切,sparseBooleanArray将等于所有项目所有选定的清单。

但是,据我所知spareBooleanArray是一个数组,它存储的位置和一个布尔标志,如果它被选中或不。在我的场景中,当我按下第三个选择按钮时,数组的大小仍然等于列表项的数量。

我如何解决我的问题,是使用getCheckedItemCount(),它只返回所选项目的数量,正如我最初想要的。希望这个答案会帮助别人。

int childCount = officerList.getChildCount(); 
int selectedCount = officerList.getCheckedItemCount(); 

     if(childCount != selectedCount){ 
      for (int i = 0; i < officerList.getChildCount(); i++) { 
       officerList.setItemChecked(i, true); 
      } 
     }else{ 
      for (int i = 0; i < officerList.getChildCount(); i++) { 
       officerList.setItemChecked(i, false); 
      } 
     } 
    } 
0

试试这个逻辑,它会检查所有的项目,如果没有项目被检查,否则将只检查未选中的项目,反之亦然。

public void onClick(View v) { 
     SparseBooleanArray sparseBooleanArray = officerList.getCheckedItemPositions(); 
     if(sparseBooleanArray != null && sparseBooleanArray.size() >0) { 
      for (int index = 0; index < sparseBooleanArray.size(); index++) { 
       if(sparseBooleanArray.valueAt(index)){ 
         officerList.setItemChecked(sparseBooleanArray.keyAt(index),true); 
        } 
        else { 
         officerList.setItemChecked(sparseBooleanArray.keyAt(index),false); 
        } 
       } 
      } 
      else { 
       for (int index = 0; index < officerList.getCount(); index++) { 
        officerList.setItemChecked(index,true); 
       } 
      } 
     } 
相关问题