Android自定义单例AlertDialog详解

发布时间 - 2026-01-11 02:59:31    点击率:

当Android开发处理错误信息时,经常会以Dialog的形式显示错误信息,但是每次都new一个Dialog,很麻烦,也增加程序的开销,所以今天就分享一种自定义单例AlertDialog

public class AlertDialog {
  private static AlertDialog alertDialog = null;
  private Context context;
  private Dialog dialog;
  private LinearLayout lLayout_bg;
  private TextView txt_title;
  private TextView txt_msg;
  private Button btn_neg;
  private Button btn_pos;
  private ImageView img_line;
  private Display display;
  private boolean showTitle = false;
  private boolean showMsg = false;
  private boolean showPosBtn = false;
  private boolean showNegBtn = false;

  public static AlertDialog getInstance(Context context){
    if (alertDialog==null){
      synchronized (AlertDialog.class) {
        if (alertDialog == null) {
          alertDialog = new AlertDialog(context).builder();
        }
      }
    }
    return alertDialog;
  }
  public AlertDialog(Context context) {
    this.context = context;
    WindowManager windowManager = (WindowManager) context
        .getSystemService(Context.WINDOW_SERVICE);
    display = windowManager.getDefaultDisplay();
  }

  public AlertDialog builder() {
    // 获取Dialog布局
    View view = LayoutInflater.from(context).inflate(R.layout.view_alertdialog, null);

    // 获取自定义Dialog布局中的控件
    lLayout_bg = (LinearLayout) view.findViewById(R.id.lLayout_bg);
    txt_title = (TextView) view.findViewById(R.id.txt_title);
    txt_title.setVisibility(View.GONE);
    txt_msg = (TextView) view.findViewById(R.id.txt_msg);
    txt_msg.setVisibility(View.GONE);
    btn_neg = (Button) view.findViewById(R.id.btn_neg);
    btn_neg.setVisibility(View.GONE);
    btn_pos = (Button) view.findViewById(R.id.btn_pos);
    btn_pos.setVisibility(View.GONE);
    img_line = (ImageView) view.findViewById(R.id.img_line);
    img_line.setVisibility(View.GONE);

    // 定义Dialog布局和参数
    dialog = new Dialog(context, R.style.AlertDialogStyle);
    dialog.setContentView(view);

    // 调整dialog背景大小
    lLayout_bg.setLayoutParams(new FrameLayout.LayoutParams((int) (display
        .getWidth() * 0.85), LayoutParams.WRAP_CONTENT));

    return this;
  }

  public AlertDialog setTitle(String title) {
    showTitle = true;
    if ("".equals(title)) {
      txt_title.setText("标题");
    } else {
      txt_title.setText(title);
    }
    return this;
  }

  public AlertDialog setMsg(String msg) {
    showMsg = true;
    if ("".equals(msg)) {
      txt_msg.setText("内容");
    } else {
      txt_msg.setText(msg);
    }
    return this;
  }
  public AlertDialog setMsg(int rId) {
    showMsg = true;
    txt_msg.setText(rId);
    return this;
  }

  public AlertDialog setCancelable(boolean cancel) {
    dialog.setCancelable(cancel);
    return this;
  }

  public AlertDialog setPositiveButton(String text,
      final OnClickListener listener) {
    showPosBtn = true;
    if ("".equals(text)) {
      btn_pos.setText("确定");
    } else {
      btn_pos.setText(text);
    }
    btn_pos.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        if(listener!=null) {
          listener.onClick(v);
        }
        dialog.dismiss();
      }
    });
    return this;
  }

  public AlertDialog setNegativeButton(String text,
      final OnClickListener listener) {
    showNegBtn = true;
    if ("".equals(text)) {
      btn_neg.setText("取消");
    } else {
      btn_neg.setText(text);
    }
    btn_neg.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        if(listener!=null) {
          listener.onClick(v);
        }
        dialog.dismiss();
      }
    });
    return this;
  }

  private void setLayout() {
    if (!showTitle && !showMsg) {
      txt_title.setText("");
      txt_title.setVisibility(View.VISIBLE);
    }

    if (showTitle) {
      txt_title.setVisibility(View.VISIBLE);
    }

    if (showMsg) {
      txt_msg.setVisibility(View.VISIBLE);
    }

    if (!showPosBtn && !showNegBtn) {
      btn_pos.setText("确定");
      btn_pos.setVisibility(View.VISIBLE);
      btn_pos.setBackgroundResource(R.drawable.alertdialog_single_selector);
      btn_pos.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
          dialog.dismiss();
        }
      });
    }

    if (showPosBtn && showNegBtn) {
      btn_pos.setVisibility(View.VISIBLE);
      btn_pos.setBackgroundResource(R.drawable.alertdialog_right_selector);
      btn_neg.setVisibility(View.VISIBLE);
      btn_neg.setBackgroundResource(R.drawable.alertdialog_left_selector);
      img_line.setVisibility(View.VISIBLE);
    }

    if (showPosBtn && !showNegBtn) {
      btn_pos.setVisibility(View.VISIBLE);
      btn_pos.setBackgroundResource(R.drawable.alertdialog_single_selector);
    }

    if (!showPosBtn && showNegBtn) {
      btn_neg.setVisibility(View.VISIBLE);
      btn_neg.setBackgroundResource(R.drawable.alertdialog_single_selector);
    }
  }

  public void show() {
    setLayout();
    dialog.show();
  }
}

布局文件view_alertdialog.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/lLayout_bg"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:background="@drawable/alert_bg"
  android:orientation="vertical">

  <TextView
    android:id="@+id/txt_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:layout_marginTop="15dp"
    android:gravity="center"
    android:text="提示"
    android:textColor="@color/black"
    android:textSize="18dp" />


  <TextView
    android:id="@+id/txt_msg"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:gravity="center"
    android:text="您确定要退出吗?"
    android:textColor="@color/black"
    android:textSize="16dp" />

  <ImageView
    android:layout_width="match_parent"
    android:layout_height="0.5dp"
    android:layout_marginTop="10dp"
    android:background="@color/alertdialog_line" />

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
      android:id="@+id/btn_neg"
      android:layout_width="wrap_content"
      android:layout_height="43dp"
      android:layout_weight="1"
      android:background="@drawable/alertdialog_left_selector"
      android:gravity="center"
      android:text="确定"
      android:textColor="@color/bigtextcolor"
      android:textSize="16sp" />

    <ImageView
      android:id="@+id/img_line"
      android:layout_width="0.5dp"
      android:layout_height="43dp"
      android:background="@color/alertdialog_line" />

    <Button
      android:id="@+id/btn_pos"
      android:layout_width="wrap_content"
      android:layout_height="43dp"
      android:layout_weight="1"
      android:background="@drawable/alertdialog_right_selector"
      android:gravity="center"
      android:text="取消"
      android:textColor="@color/themecolor"
      android:textSize="16sp" />
  </LinearLayout>

</LinearLayout>

效果显示

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


# Android  # 单例  # AlertDialog  # Android AlertDialog的几种用法详解  # Android中AlertDialog四种对话框的最科学编写用法(实例代码)  # Android去除AlertDialog的按钮栏的分隔线  # Android编程自定义AlertDialog样式的方法详解  # Android使用AlertDialog创建对话框  # Android开发实现AlertDialog中View的控件设置监听功能分析  # Android 自定义AlertDialog对话框样式  # Android AlertDialog多种创建方式案例详解  # 自定义  # 错误信息  # 每次都  # 会以  # 大家多多  # 很麻烦  # View 


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


相关推荐: 如何在服务器上配置二级域名建站?  详解Android图表 MPAndroidChart折线图  新三国志曹操传主线渭水交兵攻略  香港服务器部署网站为何提示未备案?  安克发布新款氮化镓充电宝:体积缩小 30%,支持 200W 输出  如何在VPS电脑上快速搭建网站?  laravel怎么用DB facade执行原生SQL查询_laravel DB facade原生SQL执行方法  如何制作公司的网站链接,公司想做一个网站,一般需要花多少钱?  详解Nginx + Tomcat 反向代理 负载均衡 集群 部署指南  Laravel如何实现数据导出到PDF_Laravel使用snappy生成网页快照PDF【方案】  Laravel如何操作JSON类型的数据库字段?(Eloquent示例)  如何制作一个表白网站视频,关于勇敢表白的小标题?  如何撰写建站申请书?关键要点有哪些?  如何在建站之星绑定自定义域名?  如何快速搭建高效可靠的建站解决方案?  laravel怎么实现图片的压缩和裁剪_laravel图片压缩与裁剪方法  Linux系统运维自动化项目教程_Ansible批量管理实战  Python函数文档自动校验_规范解析【教程】  Laravel控制器是什么_Laravel MVC架构中Controller的作用与实践  Python文件流缓冲机制_IO性能解析【教程】  如何在建站主机中优化服务器配置?  Linux系统命令中tree命令详解  linux top下的 minerd 木马清除方法  Laravel怎么集成Vue.js_Laravel Mix配置Vue开发环境  HTML透明颜色代码怎么让下拉菜单透明_下拉菜单透明背景指南【技巧】  高端建站三要素:定制模板、企业官网与响应式设计优化  成都品牌网站制作公司,成都营业执照年报网上怎么办理?  利用vue写todolist单页应用  b2c电商网站制作流程,b2c水平综合的电商平台?  Laravel如何使用Socialite实现第三方登录?(微信/GitHub示例)  简单实现jsp分页  微信小程序 五星评分(包括半颗星评分)实例代码  Windows11怎样设置电源计划_Windows11电源计划调整攻略【指南】  PHP正则匹配日期和时间(时间戳转换)的实例代码  JavaScript如何实现音频处理_Web Audio API如何工作?  Python文件操作最佳实践_稳定性说明【指导】  php中::能调用final静态方法吗_final修饰静态方法调用规则【解答】  香港服务器网站卡顿?如何解决网络延迟与负载问题?  如何做网站制作流程,*游戏网站怎么搭建?  微信小程序 input输入框控件详解及实例(多种示例)  Laravel怎么上传文件_Laravel图片上传及存储配置  Laravel怎么在Blade中安全地输出原始HTML内容  Laravel如何使用Eloquent进行子查询  Laravel如何使用Vite进行前端资源打包?(配置示例)  如何在万网自助建站平台快速创建网站?  Laravel如何优化应用性能?(缓存和优化命令)  Laravel如何发送邮件_Laravel Mailables构建与发送邮件的简明教程  香港服务器如何优化才能显著提升网站加载速度?  php静态变量怎么调试_php静态变量作用域调试技巧【解答】  Laravel如何正确地在控制器和模型之间分配逻辑_Laravel代码职责分离与架构建议