2013-01-10 50 views
0

我想使用「SelectAll」和「DeselectAll」按鈕選擇並取消選擇列表視圖中的所有項目。我編寫了SelectAll的代碼,但它拋出了一個NullPointException。我找不到我的代碼中的錯誤。有人可以指出我的代碼中的錯誤。使用自定義列表視圖中的按鈕選擇所有項目

final ListView list; 
String[] listItems = { "Enabled" }; 

list = (ListView)findViewById(R.id.list); 

list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, getResources().getStringArray(R.array.facilities))); 
list.setItemsCanFocus(false); 
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);          

list.setOnItemClickListener(new OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 
     CheckedTextView ctv = (CheckedTextView)arg1; 
     //other functionality!            
    } 
}); 

OnClickListener clickListener = new OnClickListener() { 
    @Override 
    public void onClick(View view) { 
     int itemCount = getListView().getCount(); 
     System.out.print(itemCount); 
     for (int i = 0; i < itemCount; i++){ 
      list.setItemChecked(i, true); 
      //getListView().setItemChecked(i, chk.isChecked()); 
     } 
    } 
}; 

Button button = (Button) findViewById(R.id.selectAll); 
button.setOnClickListener(clickListener); 

回答

0

嘗試使用下面的代碼...

private OnClickListener checkAllCheckboxes = new OnClickListener() 
{ 
    public void onClick(View v) 
    { 
     ListView lv = getListView(); 
     int size = getListAdapter().getCount(); 
     if(lv.isItemChecked(0)) 
     { 
      for(int i = 0; i<=size; i++) 
      { 
       lv.setItemChecked(i, false); 
      } 
     } 
    } 
} 
}; 
+0

我用上面的代碼,但仍然面臨同樣的錯誤。應用程序意外關閉,並拋出NullPointException。 – bunnie

+0

因爲在上面的代碼中使用了getListAdapter(),我的MainActivity是否應該擴展ListActivity以具有getListAdapter方法?如果我這樣做,我得到了「RunTimeException:你的內容應該有一個ListView,其ID爲android.R.id.list」 – bunnie

+0

在你的xml文件中,你必須使用android:id =「@ android:id/list」 –

0

您可以創建數據類的一個ArrayList的

class data 
{ 
boolean chekced=false 
create setter and getter of this 

} 

創建數據類的ArrayList intially Chekced是在所有的數組列表項錯誤 當選擇被稱爲設置所有項目爲真 然後moify adpater和調用notifyDatasetChanged listView

這就是你如何做到這一點

相關問題