Android的DialogActivity如何实现多选和单选功能

avatar
作者
筋斗云
阅读量:0

要实现多选和单选功能,可以使用AlertDialog.Builder类来创建一个对话框并设置多选和单选选项。以下是一个示例代码:

  1. 单选功能:
AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("选择一个选项"); final String[] items = {"选项1", "选项2", "选项3"};  builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {     @Override     public void onClick(DialogInterface dialog, int which) {         // 点击选项时的操作         Toast.makeText(DialogActivity.this, "你选择了:" + items[which], Toast.LENGTH_SHORT).show();         dialog.dismiss();     } });  builder.create().show(); 
  1. 多选功能:
AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("选择多个选项"); final String[] items = {"选项1", "选项2", "选项3"}; final boolean[] checkedItems = {false, false, false};  builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {     @Override     public void onClick(DialogInterface dialog, int which, boolean isChecked) {         // 多选项点击时的操作         checkedItems[which] = isChecked;     } });  builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {     @Override     public void onClick(DialogInterface dialog, int which) {         // 点击确定按钮时的操作         StringBuilder selectedItems = new StringBuilder();         for (int i = 0; i < items.length; i++) {             if (checkedItems[i]) {                 selectedItems.append(items[i]).append(" ");             }         }         Toast.makeText(DialogActivity.this, "你选择了:" + selectedItems.toString(), Toast.LENGTH_SHORT).show();         dialog.dismiss();     } });  builder.create().show(); 

通过以上代码示例,可以实现在DialogActivity中实现多选和单选功能。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!