要實現多選和單選功能,可以使用AlertDialog.Builder類來創建一個對話框并設置多選和單選選項。以下是一個示例代碼:
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();
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中實現多選和單選功能。