Android中常见的对话框
1. 普通对话框
1 public void click01(View view){ 2 AlertDialog.Builder builder = new AlertDialog.Builder(this);//内部类 3 builder.setTitle("友情提示"); 4 builder.setMessage("您确定要删除吗?"); 5 //确定按钮 6 builder.setPositiveButton("确定", new OnClickListener() { 7 8 @Override 9 public void onClick(DialogInterface dialog, int which) { 10 //确定删除的代码 11 Toast.makeText(MainActivity.this, "删除成功", 0).show(); 12 } 13 }); 14 //点取消按钮 15 builder.setNegativeButton("取消", null); 16 17 //显示对话框 18 //AlertDialog dialog = builder.create(); 19 //dialog.show(); 20 //或者简单点 21 builder.show(); 22 }
显示的效果:
2. 单选对话框
1 public void click02(View view){ 2 AlertDialog.Builder builder = new AlertDialog.Builder(this); 3 4 final String[] items = {"男","女","其他"}; 5 6 builder.setSingleChoiceItems(items, 0, new OnClickListener() { 7 8 @Override 9 public void onClick(DialogInterface dialog, int which) { 10 String item = items[which]; 11 Toast.makeText(MainActivity.this, "您选择的是: "+ item, 0).show(); 12 } 13 }); 14 15 //显示对话框 16 builder.show(); 17 }
显示的效果:
3. 多选对话框
public void click03(View view){ AlertDialog.Builder builder = new AlertDialog.Builder(this); final String[] items = {"篮球","乒乓球","羽毛球","台球","玻璃球"}; boolean[] checkedItems = {true,false,false,true,false}; builder.setMultiChoiceItems(items, checkedItems, new OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { String item = items[which]; Toast.makeText(MainActivity.this, "您选择的爱好是: "+ item+",状态是: "+isChecked, 0).show(); } }); //显示 builder.show(); }
显示的效果:
4. 不带进度条的对话框
1 public void click04(View view){ 2 final ProgressDialog pd = ProgressDialog.show(this, "不带进度条", "一大波美女袭来"); 3 new Thread(){ 4 public void run() { 5 SystemClock.sleep(2000); 6 pd.dismiss(); 7 }; 8 }.start(); 9 }
显示的效果:
5. 带进度条的对话框
1 public void click05(View view){ 2 final ProgressDialog pd = new ProgressDialog(this); 3 //设置水平的进度条样式 4 pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 5 pd.setMax(100); 6 pd.show(); 7 new Thread(){ 8 public void run() { 9 for (int i = 0; i < 100; i++) { 10 SystemClock.sleep(50); 11 pd.setProgress(i); 12 } 13 pd.dismiss(); 14 }; 15 }.start(); 16 }
显示的效果: