【Android笔记——AlertDialog】点击EditText弹出单选框或多选框
怕以后自己忘了,只是记录一下,直接上代码吧
实现单选
// et_form_hint是EditText的id
et_form_hint.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String[] choiceItems = new String[]{"A", "B", "C", "D"};
AlertDialog.Builder builder = new AlertDialog.Builder(activity); // activity是当前所显示的activity
builder.setItems(choiceItems, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
et_form_hint.setText(choiceItems[which]);
}
});
builder.show();
});
实现多选
et_form_hint.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 多选
final String[] choiceItems = new String[]{"A", "B", "C", "D", "E"}
final boolean[] selectedItems = new boolean[choiceItems.length];
Arrays.fill(selectedItems, false);
Dialog alertDialog = new AlertDialog.Builder(activity).setTitle("")
.setMultiChoiceItems(choiceItems, selectedItems, new
DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
selectedItems[which] = isChecked;
}
}).setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
StringBuilder stringBuilder = new StringBuilder();
String choice[] = new String[choiceItems.length];
int j = 0;
for (int i = 0; i < selectedItems.length; i++) {
if(selectedItems[i] == true) {
choice[j++] = choiceItems[i];
}
}
for(int i = 0; i < j; i++) {
stringBuilder.append(choice[i]);
if(j - 1 != i ) {
stringBuilder.append(",");
}
}
et_form_hint.setText(stringBuilder);
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
alertDialog.show();
});
参考文章1——【Android新手笔记一】编辑框edittext实现单选或多选等对话框
参考文章2——EditText点击事件:弹出单选框