显示提示框很容易,一般提示框中可以显示的按钮有一个确定按钮,一个取消按钮,有时候可能需要三个按钮比如是、否和取消。 最简单的是至少显示一个按钮,然后给按钮添加事件以便监听用户的行为 显示一个提示框中主要的内容包括标题,内容和按钮 一个按钮的示例
AlertDialog alertDialog = new AlertDialog.Builder(
AlertDialogActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Welcome to fullstacks.cn");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
两个按钮的示例
AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm Delete...");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want delete this?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.delete);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
}
});
运行的效果图
三个按钮的示例
AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Save File...");
// Setting Dialog Message
alertDialog.setMessage("Do you want to save this file?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.save);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// User pressed YES button. Write Logic Here
Toast.makeText(getApplicationContext(), "You clicked on YES",
Toast.LENGTH_SHORT).show();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// User pressed No button. Write Logic Here
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
}
});
// Setting Netural "Cancel" Button
alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// User pressed Cancel button. Write Logic Here
Toast.makeText(getApplicationContext(), "You clicked on Cancel",
Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
运行之后的效果
总结 系统默认的提示框是简单的显示文本信息再加上一些图标,已提示用户系统中正要做的一些重要事件,由用户做最终决定是否执行,这种提示框是比较简单,如果需要复杂的提示框,可以采用对话框的模式,可以通过自定页面布局达到复杂的业务要求。