一般对话框
//一般对话框
public void bt_1(View v) {
//不能直接实例化
//内部提供构造器
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("确认对话框")
.setMessage("确定删除?")
.setPositiveButton("确认", new DialogInterface.OnClickListener() {//正向按钮
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(Text5Activity.this, "执行删除,which=" + which, Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {//负面按钮
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(Text5Activity.this, "取消删除,which=" + which, Toast.LENGTH_SHORT).show();
}
})
.setNeutralButton("中立", new DialogInterface.OnClickListener() {//中立按钮
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(Text5Activity.this, "普通按钮,+which=" + which, Toast.LENGTH_SHORT).show();
}
})
.setCancelable(false)
.show();//显示对话框
}
单选对话框
//单选对话框
public void bt_2(View v) {
//String终态,可以让这个常量的生命周期延长到整个实例
final String[] str = {"男", "女"};
new AlertDialog.Builder(this)
.setTitle("单选对话框")
.setSingleChoiceItems(str, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(Text5Activity.this, "which=" + which + "选中的值是" + str[which], Toast.LENGTH_SHORT).show();
//点击关闭对话框
//a.dismiss();不能在内部用
dialog.dismiss();
}
})
.setCancelable(false)
.show();
}
复选对话框
//复选对话框
public void bt_3(View v)
{
final String []str={"宝马","奔驰","奇瑞","宾利"};
final boolean[]ch={true,false,false,true};
new AlertDialog.Builder(this)
.setTitle("复选对话框")
.setMultiChoiceItems(str, ch, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
//改变对应项的选中状态
ch[which]=isChecked;
}
})
.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int i = 0;
//获取最终选择状态
for (boolean b : ch) {
Toast.makeText(Text5Activity.this, str[i] + "选中状态=" + (b ? "选中" : "未选中"), Toast.LENGTH_LONG).show();
i++;
}
}
})
.setNegativeButton("取消", null)
.setCancelable(false)
.show();
}