mardi 17 mars 2015

ListView with CheckBox, Check all checkbox does the opposite

I am trying to implement a listview with checkbox with a check all button. However, when I check the check all checkbox the opposite happens, all checkboxes gets unchecked and when I uncheck the check all checkbox, the boxes gets checked. Here is my code:



chkall = (CheckBox) findViewById(R.id.chkAll);
//chkall.setChecked(false);
/** Defining array adapter to store items for the listview **/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, names);

/** Setting the arrayadapter for this listview **/
getListView().setAdapter(adapter);

/** Defining checkbox click event listener **/
OnClickListener clickListener = new OnClickListener() {
@Override
public void onClick(View v) {
CheckBox chk = (CheckBox) v;
int itemCount = getListView().getCount();
for(int i=0 ; i < itemCount ; i++){
getListView().setItemChecked(i, chk.isChecked());

}



}
};

/** Defining click event listener for the listitem checkbox */
OnItemClickListener itemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {

int checkedItemCount = getCheckedItemCount();

if(getListView().getCount()==checkedItemCount)
chkall.setChecked(false);
else
chkall.setChecked(true);


// String attID =scoresDataBaseAdapter.getAttID(perd,mRowId);
//scoresDataBaseAdapter.insertAttScore(perd,mRowId,attID,Sname,idstud,score);
// Toast.makeText(getApplicationContext(), " "+arg0+" "+arg1+" "+arg2+" "+arg3, Toast.LENGTH_SHORT).show();



}
};

/** Getting reference to checkbox available in the main.xml layout */
CheckBox chkAll = ( CheckBox ) findViewById(R.id.chkAll);

/** Setting a click listener for the checkbox **/
chkAll.setOnClickListener(clickListener);

/** Setting a click listener for the listitem checkbox **/
getListView().setOnItemClickListener(itemClickListener);

}

/**
*
* Returns the number of checked items
*/
private int getCheckedItemCount(){
int cnt = 0;
SparseBooleanArray positions = getListView().getCheckedItemPositions();
int itemCount = getListView().getCount();

for(int i=0;i<itemCount;i++){
if(positions.get(i))
cnt++;
}

return cnt;
}




Aucun commentaire:

Enregistrer un commentaire