Android的八种对话框的实现代码示例

发布时间 - 2026-01-11 03:11:33    点击率:

1.写在前面

Android提供了丰富的 Dialog 函数,本文介绍最常用的8种对话框的使用方法,包括普通(包含提示消息和按钮)、列表、单选、多选、等待、进度条、编辑、自定义等多种形式,将在第2部分介绍。

有时,我们希望在对话框创建或关闭时完成一些特定的功能,这需要复写
Dialog的create()、show()、dismiss()等方法,将在第3部分介绍。

2.代码示例

2.1 普通Dialog(图1与图2)

2个按钮

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button buttonNormal = (Button) findViewById(R.id.button_normal);
    buttonNormal.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        showNormalDialog();
      }
    });
  }
  
  private void showNormalDialog(){
    /* @setIcon 设置对话框图标
     * @setTitle 设置对话框标题
     * @setMessage 设置对话框消息提示
     * setXXX方法返回Dialog对象,因此可以链式设置属性
     */
    final AlertDialog.Builder normalDialog = 
      new AlertDialog.Builder(MainActivity.this);
    normalDialog.setIcon(R.drawable.icon_dialog);
    normalDialog.setTitle("我是一个普通Dialog")
    normalDialog.setMessage("你要点击哪一个按钮呢?");
    normalDialog.setPositiveButton("确定", 
      new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        //...To-do
      }
    });
    normalDialog.setNegativeButton("关闭", 
      new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        //...To-do
      }
    });
    // 显示
    normalDialog.show();
  }
}

3个按钮

/* @setNeutralButton 设置中间的按钮
 * 若只需一个按钮,仅设置 setPositiveButton 即可
 */
private void showMultiBtnDialog(){
  AlertDialog.Builder normalDialog = 
    new AlertDialog.Builder(MainActivity.this);
  normalDialog.setIcon(R.drawable.icon_dialog);
  normalDialog.setTitle("我是一个普通Dialog").setMessage("你要点击哪一个按钮呢?");
  normalDialog.setPositiveButton("按钮1", 
    new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      // ...To-do
    }
  });
  normalDialog.setNeutralButton("按钮2", 
    new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      // ...To-do
    }
  });
  normalDialog.setNegativeButton("按钮3", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      // ...To-do
    }
  });
  // 创建实例并显示
  normalDialog.show();
}

2.2 列表Dialog(图3)

private void showListDialog() {
  final String[] items = { "我是1","我是2","我是3","我是4" };
  AlertDialog.Builder listDialog = 
    new AlertDialog.Builder(MainActivity.this);
  listDialog.setTitle("我是一个列表Dialog");
  listDialog.setItems(items, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      // which 下标从0开始
      // ...To-do
      Toast.makeText(MainActivity.this, 
        "你点击了" + items[which], 
        Toast.LENGTH_SHORT).show();
    }
  });
  listDialog.show();
}

2.3 单选Dialog(图4)

int yourChoice;
private void showSingleChoiceDialog(){
  final String[] items = { "我是1","我是2","我是3","我是4" };
  yourChoice = -1;
  AlertDialog.Builder singleChoiceDialog = 
    new AlertDialog.Builder(MainActivity.this);
  singleChoiceDialog.setTitle("我是一个单选Dialog");
  // 第二个参数是默认选项,此处设置为0
  singleChoiceDialog.setSingleChoiceItems(items, 0, 
    new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      yourChoice = which;
    }
  });
  singleChoiceDialog.setPositiveButton("确定", 
    new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      if (yourChoice != -1) {
        Toast.makeText(MainActivity.this, 
        "你选择了" + items[yourChoice], 
        Toast.LENGTH_SHORT).show();
      }
    }
  });
  singleChoiceDialog.show();
}

2.4 多选Dialog(图5)

ArrayList<Integer> yourChoices = new ArrayList<>();
private void showMultiChoiceDialog() {
  final String[] items = { "我是1","我是2","我是3","我是4" };
  // 设置默认选中的选项,全为false默认均未选中
  final boolean initChoiceSets[]={false,false,false,false};
  yourChoices.clear();
  AlertDialog.Builder multiChoiceDialog = 
    new AlertDialog.Builder(MainActivity.this);
  multiChoiceDialog.setTitle("我是一个多选Dialog");
  multiChoiceDialog.setMultiChoiceItems(items, initChoiceSets,
    new DialogInterface.OnMultiChoiceClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which,
      boolean isChecked) {
      if (isChecked) {
        yourChoices.add(which);
      } else {
        yourChoices.remove(which);
      }
    }
  });
  multiChoiceDialog.setPositiveButton("确定", 
    new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      int size = yourChoices.size();
      String str = "";
      for (int i = 0; i < size; i++) {
        str += items[yourChoices.get(i)] + " ";
      }
      Toast.makeText(MainActivity.this, 
        "你选中了" + str, 
        Toast.LENGTH_SHORT).show();
    }
  });
  multiChoiceDialog.show();
}

2.5 等待Dialog(图6)

private void showWaitingDialog() {
  /* 等待Dialog具有屏蔽其他控件的交互能力
   * @setCancelable 为使屏幕不可点击,设置为不可取消(false)
   * 下载等事件完成后,主动调用函数关闭该Dialog
   */
  ProgressDialog waitingDialog= 
    new ProgressDialog(MainActivity.this);
  waitingDialog.setTitle("我是一个等待Dialog");
  waitingDialog.setMessage("等待中...");
  waitingDialog.setIndeterminate(true);
  waitingDialog.setCancelable(false);
  waitingDialog.show();
}

2.6 进度条Dialog(图7)

private void showProgressDialog() {
  /* @setProgress 设置初始进度
   * @setProgressStyle 设置样式(水平进度条)
   * @setMax 设置进度最大值
   */
  final int MAX_PROGRESS = 100;
  final ProgressDialog progressDialog = 
    new ProgressDialog(MainActivity.this);
  progressDialog.setProgress(0);
  progressDialog.setTitle("我是一个进度条Dialog");
  progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  progressDialog.setMax(MAX_PROGRESS);
  progressDialog.show();
  /* 模拟进度增加的过程
   * 新开一个线程,每个100ms,进度增加1
   */
  new Thread(new Runnable() {
    @Override
    public void run() {
      int progress= 0;
      while (progress < MAX_PROGRESS){
        try {
          Thread.sleep(100);
          progress++;
          progressDialog.setProgress(progress);
        } catch (InterruptedException e){
          e.printStackTrace();
        }
      }
      // 进度达到最大值后,窗口消失
      progressDialog.cancel();
    }
  }).start();
}

2.7 编辑Dialog(图8)

private void showInputDialog() {
  /*@setView 装入一个EditView
   */
  final EditText editText = new EditText(MainActivity.this);
  AlertDialog.Builder inputDialog = 
    new AlertDialog.Builder(MainActivity.this);
  inputDialog.setTitle("我是一个输入Dialog").setView(editText);
  inputDialog.setPositiveButton("确定", 
    new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      Toast.makeText(MainActivity.this,
      editText.getText().toString(), 
      Toast.LENGTH_SHORT).show();
    }
  }).show();
}

2.8 自定义Dialog(图9)

<!-- res/layout/dialog_customize.xml-->
<!-- 自定义View -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <EditText
    android:id="@+id/edit_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
    />
</LinearLayout>
private void showCustomizeDialog() {
  /* @setView 装入自定义View ==> R.layout.dialog_customize
   * 由于dialog_customize.xml只放置了一个EditView,因此和图8一样
   * dialog_customize.xml可自定义更复杂的View
   */
  AlertDialog.Builder customizeDialog = 
    new AlertDialog.Builder(MainActivity.this);
  final View dialogView = LayoutInflater.from(MainActivity.this)
    .inflate(R.layout.dialog_customize,null);
  customizeDialog.setTitle("我是一个自定义Dialog");
  customizeDialog.setView(dialogView);
  customizeDialog.setPositiveButton("确定",
    new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      // 获取EditView中的输入内容
      EditText edit_text = 
        (EditText) dialogView.findViewById(R.id.edit_text);
      Toast.makeText(MainActivity.this,
        edit_text.getText().toString(),
        Toast.LENGTH_SHORT).show();
    }
  });
  customizeDialog.show();
}

3.复写回调函数

/* 复写Builder的create和show函数,可以在Dialog显示前实现必要设置
 * 例如初始化列表、默认选项等
 * @create 第一次创建时调用
 * @show 每次显示时调用
 */
private void showListDialog() {
  final String[] items = { "我是1","我是2","我是3","我是4" };
  AlertDialog.Builder listDialog = 
    new AlertDialog.Builder(MainActivity.this){
    
    @Override
    public AlertDialog create() {
      items[0] = "我是No.1";
      return super.create();
    }

    @Override
    public AlertDialog show() {
      items[1] = "我是No.2";
      return super.show();
    }
  };
  listDialog.setTitle("我是一个列表Dialog");
  listDialog.setItems(items, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      // ...To-do
    }
  });
  /* @setOnDismissListener Dialog销毁时调用
   * @setOnCancelListener Dialog关闭时调用
   */
  listDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
    public void onDismiss(DialogInterface dialog) {
      Toast.makeText(getApplicationContext(),
        "Dialog被销毁了", 
        Toast.LENGTH_SHORT).show();
    }
  });
  listDialog.show();
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


# Android  # 对话框  # 对话框实现  # android几种不同对话框的实现方式  # Android自定义dialog简单实现方法  # 7种形式的Android Dialog使用实例  # Android 自定义dialog的实现代码  # Android自定义对话框Dialog的简单实现  # 8种android 对话框(Dialog)使用方法详解  # Android 多种dialog的实现方法(推荐)  # 我是  # 我是一个  # 自定义  # 进度条  # 多选  # 你要  # 单选  # 将在  # 链式  # 设置为  # 一个普通  # 只需  # 第二个  # 新开  # 回调  # 为使  # 最常用  # 大家多多  # 均未 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 如何快速搭建个人网站并优化SEO?  使用C语言编写圣诞表白程序  如何在IIS中新建站点并配置端口与IP地址?  香港服务器租用每月最低只需15元?  Laravel Vite是做什么的_Laravel前端资源打包工具Vite配置与使用  成都品牌网站制作公司,成都营业执照年报网上怎么办理?  Laravel如何使用withoutEvents方法临时禁用模型事件  今日头条AI怎样推荐抢票工具_今日头条AI抢票工具推荐算法与筛选【技巧】  jQuery中的100个技巧汇总  米侠浏览器网页图片不显示怎么办 米侠图片加载修复  如何在云主机快速搭建网站站点?  Python面向对象测试方法_mock解析【教程】  Laravel如何生成API文档?(Swagger/OpenAPI教程)  如何确认建站备案号应放置的具体位置?  西安市网站制作公司,哪个相亲网站比较好?西安比较好的相亲网站?  Laravel怎么处理异常_Laravel自定义异常处理与错误页面教程  悟空浏览器如何设置小说背景色_悟空浏览器背景色设置【方法】  如何自定义建站之星模板颜色并下载新样式?  iOS发送验证码倒计时应用  android nfc常用标签读取总结  中国移动官方网站首页入口 中国移动官网网页登录  javascript中数组(Array)对象和字符串(String)对象的常用方法总结  Laravel如何为API编写文档_Laravel API文档生成与维护方法  php后缀怎么变mp4格式错误_修改扩展名提示格式不对怎么办【技巧】  Windows Hello人脸识别突然无法使用  Laravel如何实现图片防盗链功能_Laravel中间件验证Referer来源请求【方案】  Laravel如何实现RSS订阅源功能_Laravel动态生成网站XML格式订阅内容【教程】  如何用低价快速搭建高质量网站?  Laravel怎么在Controller之外的地方验证数据  Gemini手机端怎么发图片_Gemini手机端发图方法【步骤】  HTML透明颜色代码怎么让图片透明_给img元素加透明色的技巧【方法】  如何在Windows环境下新建FTP站点并设置权限?  php读取心率传感器数据怎么弄_php获取max30100的心率值【指南】  Laravel Eloquent访问器与修改器是什么_Laravel Accessors & Mutators数据处理技巧  谷歌浏览器下载文件时中断怎么办 Google Chrome下载管理修复  如何获取免费开源的自助建站系统源码?  悟空识字如何进行跟读录音_悟空识字开启麦克风权限与录音  电商网站制作多少钱一个,电子商务公司的网站制作费用计入什么科目?  Laravel怎么实现支付功能_Laravel集成支付宝微信支付  Laravel怎么生成二维码图片_Laravel集成Simple-QrCode扩展包与参数设置【实战】  怎么用AI帮你设计一套个性化的手机App图标?  Laravel如何将应用部署到生产服务器_Laravel生产环境部署流程  浅析上传头像示例及其注意事项  如何在 Go 中优雅地映射具有动态字段的 JSON 对象到结构体  Bootstrap整体框架之CSS12栅格系统  如何在局域网内绑定自建网站域名?  bing浏览器学术搜索入口_bing学术文献检索地址  Laravel怎么实现模型属性的自动加密  Laravel如何创建自定义Artisan命令?(代码示例)  Laravel怎么集成Log日志记录_Laravel单文件与每日日志配置及自定义通道【详解】