2014-01-11 46 views
0

我用這個例子項目試驗:http://schimpf.es/listview-with-checkboxes-inside/方法,通過chekboxes在ListView掃描

我添加包含ListView中的XML文件中的按鈕。 而當它被按下時,我想要一個方法掃描複選框數組並檢查是否全部被選中。

有人可以幫我嗎?通過數據列表中的每個條目

private boolean checkBoxes(){ 
    for(SampleData s : dataList) if (s.selected == false) return false; 
    return true; 
} 
+0

請添加一些代碼來幫助我們來幫助您。 – deW1

回答

1

試試這個。如果你得到一個沒有設置的,返回false。如果他們都經過測試返回true:

private boolean allChecked() 
{ 
    for(Object item : dataList) 
    { 
     if (!(SampleData)item.isSelected()) 
      return false; 
    } 
    return true; 
} 

注意,DataList控件被定義爲Object類型的ArrayList,而不是類型的sampleData。因此,當您迭代每個條目時,需要將其轉換爲SampleData。

編輯:

要使用此,更改活動類,以便「適配器」是一個類變量:

public class CheckboxListActivity extends ListActivity { 

    //Define adapter here so that you can refer to it anywhere within the Activity 
    CheckboxListAdapter adapter; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_checkbox); 

     //Set the class level 'adapter' variable 
     adapter = new CheckboxListAdapter(getLayoutInflater()); 
     getListView().setAdapter(adapter); 
    } 
} 

在你的onClick中,調用可變「適配器」的新方法:

public void onClickNeste_sjekkliste (View v) { 
    boolean ifCheckedAll = adapter.allChecked(); 

    if (ifCheckedAll == false) { 
     Log.d("CheckedAll", "false"); 
    } 
    else if (ifCheckedAll == true) { 
     Log.d("CheckedAll", "true"); 
    } 
} 
0

我不能得到那份工作。 它總是返回false。

我把方法進入CheckBoxListAdapter.java

public boolean allChecked() { 
    for (Object item : dataList) { 
     if (!((SampleData) item).isSelected()) 
      return false; 
    } 
    return true; 
} 

,並在我的MainActivity我調用該方法時按鈕的onClick。然後我知道它的價值。

public void onClickNeste_sjekkliste (View v) { 
    CheckboxListAdapter test = new CheckboxListAdapter(null); 
    test.allChecked(); 
    boolean ifCheckedAll = test.allChecked(); 

    if (ifCheckedAll == false) { 
     Log.d("CheckedAll", "false"); 
    } 
    else if (ifCheckedAll == true) { 
     Log.d("CheckedAll", "true"); 
    } 
} 
+0

這是因爲您正在掃描名爲'test'的全新適配器,而不是在連接到ListView的onCreate中設置的適配器。 CheckBoxListAdpater的初始狀態是true和false的混合,因此您總是會得到false。您需要在'adapter'上調用該方法。請看我更新的答案。 – NigelK