写一个java安卓CheckBox多选 的例子
时间: 2024-03-21 08:39:02 浏览: 115
好的,以下是一个简单的Java安卓CheckBox多选的例子:
1. 首先,在你的布局文件中添加一个ListView和一个Button:
```
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="@+id/select_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select All"/>
```
2. 接下来,在你的Java代码中,设置ListView的适配器:
```
ListView listView = findViewById(R.id.list_view);
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, itemList));
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
```
其中,itemList是一个包含待选择项的字符串数组。
3. 在Button的点击事件中,处理全选和取消全选:
```
Button selectButton = findViewById(R.id.select_button);
selectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (selectButton.getText().equals("Select All")) {
for (int i = 0; i < listView.getCount(); i++) {
listView.setItemChecked(i, true);
}
selectButton.setText("Deselect All");
} else {
listView.clearChoices();
selectButton.setText("Select All");
}
}
});
```
以上代码中,我们设置了一个Button的点击事件,当点击该按钮时,会根据Button的文本内容来判断是全选还是取消全选。如果是全选,则遍历ListView中的每个项并设置为选中状态;如果是取消全选,则清除ListView中所有选中的项。
注意:在运行时需要获取文件写入权限。
阅读全文
相关推荐


















