使用Alertdialog,话不多说,直接上代码
String[] items = new String[] {"xx", "yyy", "zzz"};
int selected = 0;
boolean[] selections = new boolean[] { false, false, false };
//普通对话框
public void dialog1(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Hello World").
setMessage("Hello World Text")
.setCancelable(false) //设置不可被取消
.setPositiveButton("确定", listener1)
.setNegativeButton("取消", listener1)
.setNeutralButton("稍后", listener1);
builder.show();
}
//单选对话框
public void dialog2(View v) {
new AlertDialog.Builder(this)
.setTitle("单选Demo")
.setSingleChoiceItems(items, -1, listener2)
.setPositiveButton("确定", listener2)
.show();
}
//多选对话框
public void dialog3(View v) {
new AlertDialog.Builder(this)
.setTitle("单选Demo")
.setMultiChoiceItems(items, selections, listener3)
.setPositiveButton("确定", listener4)
.show();
}
OnClickListener listener4 = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < items.length; i++) {
sb.append(selections[i] ? items[i] + " " : "");
}
Toast.makeText(getApplicationContext(), sb.toString(), Toast.LENGTH_SHORT).show();
}
};
OnMultiChoiceClickListener listener3 = new OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
selections[which] = isChecked;
System.out.println(items[which] + ": " + isChecked);
}
};
OnClickListener listener2 = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
Toast.makeText(getApplicationContext(), "确定", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), items[selected], 0).show();
break;
default:
Toast.makeText(getApplicationContext(), items[which], 0).show();
selected = which;
break;
}
}
};
OnClickListener listener1 = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
Toast.makeText(getApplicationContext(), "确定", Toast.LENGTH_SHORT).show();
break;
case DialogInterface.BUTTON_NEGATIVE:
Toast.makeText(getApplicationContext(), "取消", Toast.LENGTH_SHORT).show();
break;
case DialogInterface.BUTTON_NEUTRAL:
Toast.makeText(getApplicationContext(), "稍后", Toast.LENGTH_SHORT).show();
break;
}
}
};