下面是自己总结的Android常用的几种Dialog:
1.AlertDialog android中功能最丰富,用途最广的对话框。
// 1 创建一个Builder AlertDialog.Builder builder = new AlertDialog.Builder(this); // 2 给Builder设置属性 builder.setTitle("Java培训");// 设置Dialog的标题 builder.setMessage("访问OSC的网页");// 设置Dialog的信息 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {// 设置确定按钮 @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(), "访问OSC的网页", 0).show(); } }); builder.setNeutralButton("隐藏", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); //从上我们可以看出Dialog的按钮一般分为了三种,确定builder.setPositiveButton(),隐藏builder.setNeutralButton,取消builder.setNegativeButton // 3 创建Dialog AlertDialog dialog = builder.create(); // 4 显示Dialog dialog.show();
2.ListDialog,设置选项的时候用如下代码:
final String[] items = { "java", "donet", "php" };builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(), items[which], 0).show(); } });
3.singleItemDialog,这样子能够让选项以单选框的样式呈现出来:
builder.setSingleChoiceItems(items, 2, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(), items[which], 0).show(); } });
4.多选框的Dialog
final String[] items = { "java", "donet", "php" }; final boolean[] checkedItems = new boolean[] { true, false, false }; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("选择语言"); builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { Toast.makeText(getApplicationContext(), items[which] + isChecked, 0).show(); } });
5.进度条的dialog
ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置为水平进度条 progressDialog.setTitle("正在下载。。。"); progressDialog.setMax(100);// 设置进度条的最大值 progressDialog.setCancelable(false);// 设置回退键失效 progressDialog.setButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); progressDialog.show(); progressDialog.setProgress(50);// 设置进度条的当前刻度
注意的是Dialog是activity的一个控件,弹出Dialog的时候,activity是不会失去焦点的,也就是说activity不会调用onPause()方法