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


相关推荐: 如何用腾讯建站主机快速创建免费网站?  Python进程池调度策略_任务分发说明【指导】  Laravel PHP版本要求一览_Laravel各版本环境要求对照  高端网站建设与定制开发一站式解决方案 中企动力  PHP的CURL方法curl_setopt()函数案例介绍(抓取网页,POST数据)  Win11搜索栏无法输入_解决Win11开始菜单搜索没反应问题【技巧】  如何批量查询域名的建站时间记录?  Laravel如何发送邮件和通知_Laravel邮件与通知系统发送步骤  Laravel API路由如何设计_Laravel构建RESTful API的路由最佳实践  韩国服务器如何优化跨境访问实现高效连接?  Laravel Eloquent访问器与修改器是什么_Laravel Accessors & Mutators数据处理技巧  Laravel如何自定义分页视图?(Pagination示例)  利用 Google AI 进行 YouTube 视频 SEO 描述优化  Laravel怎么实现微信登录_Laravel Socialite第三方登录集成  如何快速搭建高效香港服务器网站?  Android使用GridView实现日历的简单功能  北京专业网站制作设计师招聘,北京白云观官方网站?  Win11搜索不到蓝牙耳机怎么办 Win11蓝牙驱动更新修复【详解】  Midjourney怎样加参数调细节_Midjourney参数调整技巧【指南】  高端建站三要素:定制模板、企业官网与响应式设计优化  Win11怎样安装网易有道词典_Win11安装词典教程【步骤】  Android实现代码画虚线边框背景效果  原生JS获取元素集合的子元素宽度实例  如何快速选择适合个人网站的云服务器配置?  Laravel观察者模式如何使用_Laravel Model Observer配置  linux top下的 minerd 木马清除方法  Laravel如何创建和注册中间件_Laravel中间件编写与应用流程  高防服务器租用如何选择配置与防御等级?  PHP怎么接收前端传的文件路径_处理文件路径参数接收方法【汇总】  Laravel如何使用Seeder填充数据_Laravel模型工厂Factory批量生成测试数据【方法】  Laravel distinct去重查询_Laravel Eloquent去重方法  在线ppt制作网站有哪些软件,如何把网页的内容做成ppt?  Laravel怎么定时执行任务_Laravel任务调度器Schedule配置与Cron设置【教程】  百度输入法全感官ai怎么关 百度输入法全感官皮肤关闭  如何在阿里云完成域名注册与建站?  如何在IIS中新建站点并配置端口与物理路径?  移动端脚本框架Hammer.js  如何用虚拟主机快速搭建网站?详细步骤解析  黑客如何利用漏洞与弱口令入侵网站服务器?  如何用好域名打造高点击率的自主建站?  Laravel中的withCount方法怎么高效统计关联模型数量  Laravel的契約(Contracts)是什么_深入理解Laravel Contracts与依赖倒置  如何在阿里云服务器自主搭建网站?  如何选择PHP开源工具快速搭建网站?  如何在云主机上快速搭建多站点网站?  Laravel如何使用Passport实现OAuth2?(完整配置步骤)  香港服务器网站测试全流程:性能评估、SEO加载与移动适配优化  如何在万网自助建站中设置域名及备案?  企业在线网站设计制作流程,想建设一个属于自己的企业网站,该如何去做?  详解Oracle修改字段类型方法总结