一、介绍:alertDialog是可以像用户发出提示信息并且能够接收到用户所反馈回来的结果信息;查看它的源码可知,它的父类是Dialog,其中的构造方法是protected修饰的,因此不能直接new去使用,在源码中可以看到有一个静态内部类Builder,可以通过此方法调用alertDialog中的方法;
二、使用:
1.创建AlertDialog.Builder对象;
AlertDialog.Builder builder= new AlertDialog.Builder();
AlertDialog dialog = builder.create();
2. 添加相关属性,常用的API有:
- setTitle():设置窗口标题
- setIcon():设置窗口图标
- setCancelable():设置是否支持取消(取消通常是指点窗口外或者点“Back”)
- setMessage():设置对话框上的提示信息
- setPositiveButton():设置确定监听器
- setNegativeButton():设置取消监听器
- setView():设置自定义布局
- dismiss():关闭弹窗;
- show():展示窗口
dialog.setTitle("XXX")...
3.其他设置:
- 更改背景颜色:
dialog.getWindow().setBackgroundDrawableResource(android.R.color.black)
- 更改按钮布局:必须在show()之后再进行处理;
- 更改窗口大小:
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//逻辑处理
dialog.dismiss();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//逻辑处理
dialog.cancel();
}
});
dialog.show();
//设置窗口宽度
Window window = dialog.getWindow();
WindowManager.LayoutParams layoutParams = window.getAttributes();
layoutParams.width = 500;
window.setAttributes(layoutParams);
//设置按钮位置
Button mNegativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
Button mPositiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
LinearLayout.LayoutParams positiveButtonLL = (LinearLayout.LayoutParams)
mPositiveButton.getLayoutParams();
positiveButtonLL.weight = 2;
mPositiveButton.setLayoutParams(positiveButtonLL);
LinearLayout.LayoutParams mNegativeButtonLL = (LinearLayout.LayoutParams)
mNegativeButton.getLayoutParams();
mNegativeButtonLL.weight = 1;
mNegativeButton.setLayoutParams(mNegativeButtonLL);
//设置按钮颜色
mPositiveButton.setTextColor(Color.RED);
mNegativeButton.setTextColor(Color.parseColor("#97999c"));