我正在尝试使用带有check all按钮的复选框来实现listview。但是,当我选中check all复选框时,相反的情况会发生,所有复选框都会被取消选中,当我取消选中check all复选框时,会选中复选框。这是我的代码:
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;
}
答案 0 :(得分:3)
您可以通过执行以下操作来撤消对setItemChecked
功能的调用:
getListView().setItemChecked(i, !chk.isChecked());