原生对话框【Dialog】AlertDialog和.Builder

使用大全
public class MainActivity extends ListActivity {
private List<String> mList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
String[] array = { "普通Dialog", "确定取消对话框 AlertDialog", "单选对话框 AlertDialog", "多选对话框 AlertDialog", //
"自定义View的Dialog---注意:不同主题下显示效果大不相同", "自定义View的AlertDialog---注意:不同主题下显示效果大不相同", //
"自定义Dialog的位置", "自定义AlertDialog的位置", //
"进度条对话框 ProgressDialog", "带进度的进度条对话框 ProgressDialog", };
for (int i = 0; i < array.length; i++) {
array[i] = i + "、" + array[i];
}
mList = new ArrayList<String>(Arrays.asList(array));
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mList));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
switch (position) {
case 0://普通Dialog
showDialog(this);
break;
case 1://确定取消对话框 AlertDialog
showSureOrCancleDialog(this);
break;
case 2://单选对话框 AlertDialog
showSingleChoiceDialog(this);
break;
case 3://多选对话框 AlertDialog
showMultiChoiceDialog(this);
break;
case 4://自定义View的Dialog---注意:不同主题下显示效果大不相同
showCustomDialog(this);
break;
case 5://自定义View的AlertDialog---注意:不同主题下显示效果大不相同
showCustomAlertDialog(this);
break;
case 6://自定义Dialog的位置
showDialogAnyWhere(this);
break;
case 7://自定义AlertDialog的位置
showAlertDialogAnyWhere(this);
break;
case 8://进度条对话框 ProgressDialog
showSimpleProgressDialog(this);
break;
case 9://带进度的进度条对话框 ProgressDialog
showProgressDialog(this);
break;
}
}
//Dialog,基本上没有什么API可用的***************************************************************************************************************
public static void showDialog(Context context) {
Dialog dialog = new Dialog(context);
dialog.setTitle("基本上没有什么API可用的");
dialog.show();
}
/**确定取消对话框,旋转屏幕后对话框消失*/
public static void showSureOrCancleDialog(final Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle("标题").setMessage("内容")//
.setCancelable(false)//点击返回键或对话框外部时是否消失,默认为true
.setNegativeButton("取消", null)//
.setPositiveButton("确定", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//参数:dialog-The dialog that received the click.;which-The button that was clicked
Toast.makeText(context, "确定被点击了", Toast.LENGTH_SHORT).show();
}
});
builder.create().show();
}
/**单选对话框*/
public static void showSingleChoiceDialog(final Context context) {
final String[] items = { "男", "女", "未知" };
AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle("请选择您的性别")//
.setSingleChoiceItems(items, -1, new OnClickListener() {//第二个参数指定选择的是哪个,-1代表默认没有选中
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "您的性别:" + items[which], Toast.LENGTH_SHORT).show();
}
}).setPositiveButton("确定", null).setNegativeButton("取消", null);
builder.create().show();
}
/**多选对话框*/
public static void showMultiChoiceDialog(final Context context) {
final String[] items = { "苹果", "梨", "菠萝", "香蕉", "黄瓜" };
final boolean[] result = new boolean[] { true, false, true, false, false };//对应条目默认是否被选中
AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle("请选择你最爱吃的水果")//
.setMultiChoiceItems(items, result, new OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
String inf = "";
if (isChecked) {
inf = " 被选中了";
} else {
inf = " 被取消选中了";
}
Toast.makeText(context, items[which] + inf, Toast.LENGTH_SHORT).show();
result[which] = isChecked;
}
})//
.setPositiveButton("提交", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < result.length; i++) {
if (result[i]) {
sb.append(items[i] + " ");
}
}
Toast.makeText(context, "您选中了:" + sb.toString(), Toast.LENGTH_SHORT).show();
}
});
builder.create().show();
}
//自定义View的Dialog。注意:不同主题下显示效果大不相同*********************************************************************************************
public static void showCustomDialog(Context context) {
Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.layout_dialog);
dialog.show();
}
public static void showCustomAlertDialog(Context context) {
new AlertDialog.Builder(context).setView(R.layout.layout_dialog).create().show();
}
//自定义对话框显示位置**********************************************************************************************************************************
public static void showDialogAnyWhere(Context context) {
Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.layout_dialog2);
Window dialogWindow = dialog.getWindow(); // 获取对话框窗口对象
dialogWindow.setBackgroundDrawable(new ColorDrawable(0xffff0000));
dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);//修改对话框的布局设置,和mLayoutParams.gravity属性的值一致
WindowManager.LayoutParams mLayoutParams = dialogWindow.getAttributes();//获取对话框参数对象
mLayoutParams.x = 0;// 表示相对于【原始位置】的偏移,当为Gravity.LEFT时就表示相对左边界的偏移,正值右移,负值忽略
mLayoutParams.y = 20;//当为Gravity.BOTTOM时正值上移,负值忽略
mLayoutParams.height = 900;//宽高设置是否有效也是和主题有关的
mLayoutParams.alpha = 0.8f; // 透明度
dialogWindow.setAttributes(mLayoutParams);
dialog.show();
}
public static void showAlertDialogAnyWhere(Context context) {
AlertDialog dialog = new AlertDialog.Builder(context).setView(R.layout.layout_dialog2).create();
Window dialogWindow = dialog.getWindow(); // 获取对话框窗口对象
dialogWindow.setBackgroundDrawable(new ColorDrawable(0xffff0000));
dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);//修改对话框的布局设置,和mLayoutParams.gravity属性的值一致
WindowManager.LayoutParams mLayoutParams = dialogWindow.getAttributes();//获取对话框参数对象
mLayoutParams.x = 0;// 表示相对于【原始位置】的偏移,当为Gravity.LEFT时就表示相对左边界的偏移,正值右移,负值忽略
mLayoutParams.y = 20;//当为Gravity.BOTTOM时正值上移,负值忽略
mLayoutParams.height = 900;//宽高设置是否有效也是和主题有关的
mLayoutParams.alpha = 0.8f; // 透明度
dialogWindow.setAttributes(mLayoutParams);
dialog.show();
}
//进度条对话框ProgressDialog********************************************************************************************************************
public static void showSimpleProgressDialog(Context context) {
final ProgressDialog pd = new ProgressDialog(context);//不需要创建器
pd.setTitle("提醒");
pd.setMessage("正在加载数据,请稍等...");
pd.setCancelable(false);
pd.show();
new Thread() {
public void run() {
SystemClock.sleep(2000);
pd.dismiss();//可以在子进程中关闭进度条。
//旋转屏幕后ProgressDialog被销毁了,而此线程会继续运行,当调用pd.dismiss()时由于pd为空,所以会导致异常。Activity直接挂掉!
};
}.start();
}
/**带进度的进度条对话框*/
public static void showProgressDialog(final Context context) {
final ProgressDialog pd = new ProgressDialog(context);
pd.setTitle("提醒");
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//当设置此属性的值后才会有进度显示
pd.setMax(100);
pd.setMessage("正在加载数据,请稍等...");
pd.setCancelable(false);
pd.show();
new Thread() {
public void run() {
for (int i = 0; i < 100; i++) {
SystemClock.sleep(20);
pd.setProgress(i);//改变当前进度。可以在子线程中改变进度条的进度。
}
pd.dismiss();//当进度为100%时关闭对话框
//仅为了演示Toast才这么搞!
Looper.prepare();
Toast.makeText(context, "加载完毕", Toast.LENGTH_SHORT).show();
Looper.loop();
};
}.start();
}
}自定义Dialog的布局1
<?xml version="1.0" encoding="utf-8"?>
<!-- 注意:不同主题下显示效果大不相同 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="180dp"
android:layout_height="400dp"
android:background="@android:color/holo_blue_light"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:inputType="textPassword" />
</LinearLayout>自定义Dialog的布局2
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_light"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:inputType="textPassword" />
</LinearLayout>Dialog相关API
public class Dialog implements DialogInterface, Window.Callback, KeyEvent.Callback, View.OnCreateContextMenuListener




AlertDialog是Dialog的一个直接子类
public class AlertDialog extends Dialog implements android.content.DialogInterface

一个AlertDialog可以有两个以上的Button,可以对一个AlertDialog设置相应的信息,比如title、massage等等。
不能直接通过AlertDialog的构造函数来生产一个AlertDialog(AlertDialog所有的构造方法都是protected),只能通过AlertDialog的静态内部类Builder来创建。

相比Dialog(基本没有什么set方法),AlertDialog使用起来相当方便,几行代码就可以搞定。
附件列表
本文来自博客园,作者:白乾涛,转载请注明原文链接:https://www.cnblogs.com/baiqiantao/p/e25f1f2003f6d76ef77322ca25821841.html
分类:
03 可能乱码的文章
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现