Android中常用的对话框总结:
确定取消对话框:
//确定取消对话框 public void onclick01(View view){ //工厂模式 AlertDialog.Builder builder = new Builder(this); //设置对话框的参数 builder.setTitle("警告"); builder.setMessage("你确定删除这份文件吗?"); //确认 builder.setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "已成功删除该文件", 0).show(); } }); //取消 builder.setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "该文件没有被删除", 0).show(); } }); AlertDialog dialog = builder.create(); dialog.show(); }
//单选对话框 public void onclick02(View view){ AlertDialog.Builder builder = new Builder(this); //设置标题 builder.setTitle("请选择你的性别?"); final String[] items = {"男","女","妖"}; builder.setSingleChoiceItems(items, 0, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Toast.makeText(MainActivity.this, items[which]+"被选中了", 0).show(); } }); builder.show(); }
//多选对话框 public void onclick03(View view){ AlertDialog.Builder builder = new Builder(this); builder.setTitle("请选择你的喜欢的水果?"); final String[] items={"香蕉","苹果","荔枝","葡萄","西瓜"}; final boolean[] checkedItems={false,true,true,false,false}; builder.setMultiChoiceItems(items, checkedItems, new OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { checkedItems[which]=isChecked; } }); //提交 builder.setPositiveButton("提交", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < checkedItems.length; i++) { if(checkedItems[i]){ sb.append(items[i]); sb.append(" "); } } Toast.makeText(MainActivity.this, "你选择了:"+sb.toString(), 0).show(); } }); builder.show(); }进度对话框:
//进度对话框 public void onclick04(View view){ final ProgressDialog dialog = new ProgressDialog(this); //设置标题 dialog.setTitle("提醒"); //设置内容 dialog.setMessage("正在提交..."); //要进行多久,一般写在另外一线程中。如果现在主线程中,会卡在这里,过一会才会显示进度对话框,这样很是不好 new Thread(){ public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { throw new RuntimeException(e); } dialog.dismiss(); }; }.start(); dialog.show(); }
//进度条对话框 public void onclick05(View view){ final ProgressDialog dialog = new ProgressDialog(this); //设置对话框进度的样式(水平方向) dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); //设置进度的最大值 dialog.setMax(100); //设置标题 dialog.setTitle("提醒"); //设置内容 dialog.setMessage("正在保存..."); new Thread(){ public void run() { for (int i = 0; i < 100; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { throw new RuntimeException(e); } dialog.setProgress(i); } dialog.dismiss(); }; }.start(); dialog.show(); }