确认取消对话框
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click1(View v) {
//使用Builder来创建
AlertDialog.Builder builder = new Builder(this);
builder.setIcon(android.R.drawable.alert_dark_frame);
builder.setTitle("欲练此功");
builder.setMessage("林平之,想清楚哦?");
//设置确定按钮
builder.setPositiveButton("必须练", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "你即将成为天下第一", 0).show();
}
});
//设置取消按钮
builder.setNegativeButton("你练我就练", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "SB,咋不练", 0).show();
}
});
//使用创建器,生成一个对话框
AlertDialog dialog = builder.create();
dialog.show();
}
}
单选对话框
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click2(View v) {
AlertDialog.Builder builder = new Builder(this);
builder.setIcon(android.R.drawable.alert_dark_frame);
builder.setTitle("请选择性别");
final String[] items = new String[] { "男", "女" };
builder.setSingleChoiceItems(items, -1, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "您选择的是:" + items[which], 0).show();
//隐藏对话框
dialog.dismiss();
}
});
builder.show();
}
}
多选对话框
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click3(View v) {
AlertDialog.Builder builder = new Builder(this);
builder.setIcon(android.R.drawable.alert_dark_frame);
builder.setTitle("请选择性别");
final String[] items = new String[] { "速度快", "收到", "第几个", "都是", "打鼓" };
final boolean[] checkedItem = new boolean[] { true, true, false, false,
false };
builder.setMultiChoiceItems(items, checkedItem,
new OnMultiChoiceClickListener() {
// 用户点击的条目下标
// 用户是选中条目还是取消条目
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
checkedItem[which] = isChecked;
}
});
builder.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
StringBuffer buf = new StringBuffer();
for (int i = 0, len = items.length; i < len; i++) {
if (checkedItem[i]) {
buf.append(items[i] + ",");
}
}
Toast.makeText(MainActivity.this, buf.toString(), 0).show();
dialog.dismiss();
}
});
builder.setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
}