代码如下:
//创建一个AlertDialog
AlertDialog.Builder ad=new AlertDialog.Builder(this);
//标题
ad.setTitle(R.string.alert_dialog_title_txt);
//内容
ad.setMessage(R.string.alert_dialog_message_txt);
// Positive Button
ad.setPositiveButton(R.string.alert_dialog_positive_txt, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//// TODO: 15/6/3
Log.d(TAG,"++++++用户点击了 Positive Button");
}
});
// Negative Button
ad.setNegativeButton(R.string.alert_dialog_negative_txt, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//// TODO: 15/6/3
Log.d(TAG,"-------用户点击了 Negative Button");
}
});
//Cancel Button
/*
*ad.setCancelable(boolean b);
* 用户在没有做任何选择而按下“返回键”时是否应该关闭AlertDialog
* true :可以关闭
* false : 不可以关闭
* */
//AlertDialog可以取消
ad.setCancelable(true);
ad.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
//// TODO: 15/6/3
Log.d(TAG,"******用户选择了取消");
}
});
//AlertDialog show
ad.show();
效果如下:
当用户点击“Yes” ,“No”和物理返回键时,可以触发相应的事件:
1》当用户点击了“Yes”时:
06-04 10:14:14.719 31083-31083/com.demo3.cxc.actionbardemo3 D/MainActivity﹕ ++++++用户点击了 Positive Button
2》当用户点击了“No”时:
06-04 10:15:10.559 31083-31083/com.demo3.cxc.actionbardemo3 D/MainActivity﹕ -------用户点击了 Negative Button
3》当用户点击返加键时:
06-04 10:15:45.329 31083-31083/com.demo3.cxc.actionbardemo3 D/MainActivity﹕ ******用户选择了取消