android如何實現ListView中的CheckBox的全選、反選、全不選 (2011-10-28 14:11:55)轉載▼ 標簽: it 分類: 移動手機應用開發 剛剛接觸android開發一個月左右,因為公司項目的需要,我不得不馬上將所學用於android平台下智能系統的開發,在開發中經常遇到問題,當然我也在這些問題中一步步成長。今天上午我遇到的問題是如何實現ListView中的CheckBox的全選、反選、全不選的功能。在網上查找了很多資料,但是貼上來都不適用,最后東拼西湊,然后結合自己項目的實際情況自己寫出了代碼實現了需要的功能。好了,在此我將代碼貼在下面,供大家學習交流之用。
1、全選
for (int index = 0; index < controlActionView.getChildCount(); index++) {
LinearLayout layout = (LinearLayout) controlActionView.getChildAt(index);
CheckBox checkBox = (CheckBox) layout.findViewById(R.id.isselected);
checkBox.setChecked(true);
}
2、反選
for (int index = 0; index < controlActionView.getChildCount(); index++) {
LinearLayout layout = (LinearLayout) controlActionView.getChildAt(index);
CheckBox checkBox = (CheckBox) layout.findViewById(R.id.isselected);
if (checkBox.isChecked()) {
checkBox.setChecked(false);
} else {
checkBox.setChecked(true);
}
}
3、全不選
for (int index = 0; index < controlActionView.getChildCount(); index++) {
LinearLayout layout = (LinearLayout) controlActionView.getChildAt(index);
CheckBox checkBox = (CheckBox) layout.findViewById(R.id.isselected);
checkBox.setChecked(false);
}
看了上面的代碼是不是很簡單呢,其實知識都這樣,編程更是如此。在遇到問題時,感覺這個問題是多么的深不可測。然后通過各種方式去查找資料解決問題。當我們找到解決方案時,感覺都很簡單。該ListView中的布局文件如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:orientation="horizontal" android:layout_height="match_parent"> <TextView android:id="@+id/controlaction_id" android:layout_height="0dip" android:layout_width="0dip" /> <TextView android:id="@+id/controlaction_code" android:layout_width="180dip" android:layout_height="wrap_content" android:textSize="15pt" /> <TextView android:id="@+id/controlaction_name" android:layout_height="wrap_content" android:layout_width="180dip" android:textSize="8pt" /> <CheckBox android:id="@+id/isselected" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>