AlertDialog.Builder dia = new AlertDialog.Builder(MainActivity.this);
dia.setTitle("是否要退出");
dia.setMessage("请选择");
// dia.setCancelable(false);
dia.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, which+"确定", Toast.LENGTH_SHORT).show();
}
});
dia.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, which+"取消", Toast.LENGTH_SHORT).show();
}
});
dia.setNeutralButton("忽略", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,which+"忽略",Toast.LENGTH_SHORT).show();
}
});
dia.show();
首先通过 AlertDialog.Builder创建出一个 AlertDialog的实例,然后可以为这个对话框设 置标题、内容、可否取消等属性,接下来调用 setPositiveButton()方法为对话框设置确定按钮 的点击事件,调用 setNegativeButton()方法设置取消按钮的点击事件,最后调用 show()方法 将对话框显示出来。
which实际上代表的是一个唯一的int型数值。像上面的setPositiveButton中的which代表的是-1,setNegativeButton中的which代表的是-3,setNeutralButton中的which代表的是-2. 到了这里相信大家已经想到怎么简洁的写法了,只要写一个响应事件,用which参数去区分是那个按钮就可以了!
DialogInterface.OnClickListener clickListene = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case Dialog.BUTTON_POSITIVE:
Toast.makeText(MainActivity.this, which + "确定", Toast.LENGTH_SHORT).show();
break;
case Dialog.BUTTON_NEGATIVE:
Toast.makeText(MainActivity.this, which + "取消", Toast.LENGTH_SHORT).show();
break;
case Dialog.BUTTON_NEUTRAL:
Toast.makeText(MainActivity.this, which + "忽略", Toast.LENGTH_SHORT).show();
break;
}
}
};
AlertDialog.Builder dia = new AlertDialog.Builder(MainActivity.this);
dia.setTitle("是否要退出");
dia.setMessage("请选择");
dia.setPositiveButton("确定", clickListene);
dia.setNegativeButton("取消",clickListene);
dia.setNeutralButton("忽略",clickListene);
dia.show();