2014-04-21 166 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); 
       } 
      } 
     } 
相關問題