继承android.app.AlertDialog
package com.jay.component;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;

import com.jay.myappstudy.R;

/**
 * 弹窗显示图片
 * */
public class AlertDialogImg extends android.app.AlertDialog {
    private Context context;
    private ImageView mImgView;
    // 图片
    private Bitmap mImg;
    // 底部按钮
    private Button btn1;
    // 当前 AlertDialogImg 实例
    private AlertDialogImg This = null;
    // 传入自定义按钮事件
    private OnClickListener mPositiveOnClick;

    public AlertDialogImg(Context context, Bitmap img) {
        super(context);
        OnCreate(context, img);
    }

    private void OnCreate(Context context, Bitmap img) {
        try {
            This = this;
            this.context = context;
            this.setCanceledOnTouchOutside(true);// 点击空白处关闭弹窗
            mImg = img;
            This.show();// 显示弹窗
            Window window = This.getWindow();// 获取窗口对象
            window.setContentView(R.layout.alert_dialog_img);// 加载布局文件
            mImgView = (ImageView) window.findViewById(R.id.img);// 获取布局文件中的控件
            if (mImgView != null) {
                mImgView.setImageBitmap(mImg);// 设置控件
            }
            btn1 = (Button) window.findViewById(R.id.btn1);// 获取按钮
            // 按钮点击事件
            btn1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 自定义按钮事件
                    if (mPositiveOnClick != null) {
                        mPositiveOnClick.onClick(This, 0);
                    }
                    // 关闭弹窗
                    This.dismiss();
                }
            });
        } catch (Exception ex) {
            Log.i("AlertDialogImg", "弹窗异常", ex);
            System.out.println(ex.getMessage());
        }
    }
    // 弹窗对象实例调用,可修改图片。
    public void setImg(Bitmap img) {
        mImgView.setImageBitmap(img);
    }

    // 弹窗对象实例调用,可修改图片。
    public void setPositiveButton(String text, final OnClickListener listener) {
        mPositiveOnClick = listener;
        btn1.setText(text);
    }
}

使用

// 生成二维码
Bitmap qrCode = QRCodeUtils.createQRCode("http://www.baidu.com", 200);
// 弹窗,一定要传Activity,弹窗是要基于Activity的。
AlertDialogImg dlg = new AlertDialogImg(currentActivity, qrCode);
// 设置弹窗底部按钮和点击事件,自定义继承View.OnClickListener
dlg.setPositiveButton("确定", null);

方式2:

                    // 创建一个 dialogView 弹窗
                    android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(currentActivity);
                    final android.app.AlertDialog dialog = builder.create();
                    // 加载布局文件
                    View dialogView = dialogView = View.inflate(curAct, R.layout.alert_dialog_img, null);
                    // 设置布局文件
                    dialog.setView(dialogView);
                    dialog.setCanceledOnTouchOutside(true);// 点击空白处关闭弹窗
                    dialog.show();// 显示弹窗
                    // 获取布局中的控件
                    ImageView img = (ImageView) dialogView.findViewById(R.id.img);
                    img.setImageBitmap(qrCode);
                    Button btn1 = (Button) dialogView.findViewById(R.id.btn1);// 获取按钮
                    btn1.setText("OK");
                    btn1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();// 关闭弹窗
                        }
                    });

布局文件:必须嵌套一个LinearLayout,否则没法自定义弹窗的宽高

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:layout_marginLeft="0px"
    android:layout_marginRight="0px"
    android:background="@drawable/bgWhite"
    android:orientation="vertical">
    <!--必须嵌套一个LinearLayout,否则不能自定义弹窗的宽高-->
    <LinearLayout
        android:layout_width="@dimen/alert_width"
        android:layout_height="@dimen/alert_height"
        android:orientation="vertical">

        <!--内容区域-->

    </LinearLayout>
</LinearLayout>

自定义弹窗宽高,此段代码必须放到 dialog.show()的后面

//获取dialog布局
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        //获取屏幕的宽高
        Point point = new Point();
        Display display = currentActivity.getWindowManager().getDefaultDisplay();
        display.getSize(point);
        //给dialog设置宽高
        params.width = getResources().getDimensionPixelSize(R.dimen.alert_width);
        params.height = getResources().getDimensionPixelSize(R.dimen.alert_height);//(int) (point.y * 0.3);
        //使设置生效
        dialog.getWindow().setAttributes(params);

倒计时弹窗

import android.content.Context;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 设备重启确认弹窗
 */
public class AlertDialogDeviceRestartConfirm extends android.app.AlertDialog {
    private Context context;
    private TextView titleView;
    private LinearLayout buttonLayout;
    private LinearLayout form;
    private String mTitle;
    private Button btn1;
    private Button btn2;
    private TextView tvCount;
    private AlertDialogDeviceRestartConfirm This = null;
    // 标记 弹窗是否已显示
    public static boolean ShowDeviceRestartConfirm = false;

    // 计时器
    private Timer timer;
    // 定时任务
    private TimerTask timerTask;
    // 5秒倒计时
    private int counts;

    /**
     * 弹窗
     */
    public AlertDialogDeviceRestartConfirm(Context context, boolean showTitle) {
        super(context);
        if (!showTitle || context == null) {
            OnCreate(context, null);
        } else {
            OnCreate(context, context.getResources().getString(R.string.app_name));
        }
    }

    public AlertDialogDeviceRestartConfirm(Context context, String Title) {
        super(context);
        OnCreate(context, Title);
    }

    /**
     * 弹窗
     */
    private void OnCreate(Context context, String Title) {
        try {
            counts = 5;
            this.setCanceledOnTouchOutside(false);
            This = this;
            mTitle = Title;
            this.context = context;
            This.show();
            // 标记弹窗是否已显示
            ShowDeviceRestartConfirm = true;
            Window window = This.getWindow();
            BaseForm.setWindowTitleHide(window);
            window.setContentView(R.layout.alert_dialog_device_restart_confirm);
            titleView = (TextView) window.findViewById(R.id.title);
            if (mTitle == null && titleView != null) {
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) titleView.getLayoutParams();
                lp.height = 0;
                titleView.setLayoutParams(lp);
                titleView.setVisibility(View.INVISIBLE);
            } else {
                this.setTitle(This.mTitle);
            }

            buttonLayout = (LinearLayout) window.findViewById(R.id.buttonLayout);
            form = (LinearLayout) titleView.getParent();
            btn1 = buttonLayout.findViewById(R.id.btnAlertDialogNo);
            btn1.setBackgroundColor(Func.getResourceColor(R.color.appMainBgColor));
            btn1.setTextColor(Func.getResourceColor(R.color.appMainTextColor));
            btn2 = buttonLayout.findViewById(R.id.btnAlertDialogYes);
            btn2.setBackgroundColor(Func.getResourceColor(R.color.appMainBgColorL6));
            btn2.setTextColor(Func.getResourceColor(R.color.appMainTextColor));
            titleView.setBackgroundColor(Func.getResourceColor(R.color.appMainBgColorL4));
            titleView.setTextColor(Func.getResourceColor(R.color.appMainTextColor));
            tvCount = window.findViewById(R.id.tvCount);
            // 确认
            btn1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    confirmIt("1");
                }
            });

            // 取消
            btn2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    confirmIt("2");
                }
            });
            // 开始定时器
            startTimer();
        } catch (
                Exception ex) {
            slog.e("AlertDialogDeviceRestartConfirm", "打开AlertDialogDeviceRestartConfirm失败", ex);
        }
    }

    /**
     * 开始定时器
     */
    private void startTimer() {
        //防止多次开启计时器
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask = null;
        }
        timerTask = new TimerTask() {
            @Override
            public void run() {
                Func.RunnableRunInUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (counts > 0) {
                            tvCount.setText("设备重启倒计时(" + String.valueOf(counts) + "秒)");
                            counts--;
                        } else {
                            // 计时结束,自动重启。
                            btn1.callOnClick();
                        }
                    }
                });
            }
        };

        timer = new Timer();
        // 定时任务,每1秒执行一次。
        timer.schedule(timerTask, 0, 1000);
    }

    /**
     * 停止定时器
     */
    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask = null;
        }
    }

    /**
     * 确认 或 取消
     */
    private void confirmIt(String status) {
        try {
            //停止定时器
            stopTimer();
            if ("1".equals(status)) {
                //重启设备
                Func.restartDevice(1);
            } else {
                //重置倒计时
                counts = 5;
                ShowDeviceRestartConfirm = false;
                //取消重启设备
                This.dismiss();
            }
        } catch (Exception ex) {
            slog.e("AlertDialogDeviceRestartConfirm", "重启设备异常", ex);
            //重置倒计时
            counts = 5;
            ShowDeviceRestartConfirm = false;
            This.dismiss();
            Func.ErrorProcDelay("重启设备异常" + ex.getMessage());
        }
    }

    @Override
    public void setTitle(int resId) {
        titleView.setText(resId);
    }

    public void setTitle(String title) {
        titleView.setText(title);
    }

    /**
     * btn1点击事件
     */
    private OnClickListener mPositiveOnClick;

    public void setPositiveButton(String text, final OnClickListener listener) {
        mPositiveOnClick = listener;
        btn1.setText(text);
    }

    /**
     * btn2点击事件
     */
    private OnClickListener mNegativeOnClick;

    public void setNegativeButton(String text, final OnClickListener listener) {
        this.mNegativeOnClick = listener;
        btn2.setText(text);
    }
}

视图文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:layout_marginLeft="0px"
    android:layout_marginRight="0px"
    android:background="@drawable/base_pannel_shape"
    android:minHeight="160dp"
    android:orientation="vertical">

    <!-- 顶部标题栏位 -->
    <TextView
        android:id="@+id/title"
        android:layout_width="fill_parent"
        android:layout_height="36dp"
        android:background="@color/appMainBgColor"
        android:gravity="center"
        android:text="重启设备"
        android:textColor="@color/appMainTextColor"
        android:textSize="14sp" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_marginLeft="20sp"
        android:layout_marginRight="20sp"
        android:layout_marginBottom="20sp"
        android:layout_weight="1"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:id="@+id/tvCount"
                android:layout_width="match_parent"
                android:layout_height="30dp"
                android:text="(5S)"
                android:textColor="@color/red"
                android:textSize="18dp"></TextView>
        </LinearLayout>
</LinearLayout>

    <!-- 在LinearLayout中加按钮 -->
    <LinearLayout
        android:id="@+id/buttonLayout"
        android:layout_width="match_parent"
        android:layout_height="40sp"
        android:orientation="horizontal">

        <LinearLayout
            android:id="@+id/plMessageBoxLeftButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" />

            <Button
                android:id="@+id/btnAlertDialogNo"
                android:layout_width="120dp"
                android:layout_height="match_parent"
                android:background="@drawable/graybutton"
                android:text="确认" />

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/plMessageBoxRightButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" />

            <Button
                android:id="@+id/btnAlertDialogYes"
                android:layout_width="120dp"
                android:layout_height="match_parent"
                android:background="@drawable/graybutton"
                android:text="取消" />

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" />
        </LinearLayout>

    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="10sp" />

</LinearLayout>

drawable/graybutton

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/btnundo1" android:state_pressed="false"/>
    <item android:drawable="@drawable/btnundo2" android:state_pressed="true"/>
    <item android:drawable="@drawable/btnundo1"/>
</selector>

其他

/**
     * 设备重启弹窗
     * */
    public static void MessageBoxDeviceRestartConfirm(android.content.DialogInterface.OnClickListener yesClick,
                                                  android.content.DialogInterface.OnClickListener noClick) {
        AlertDialogDeviceRestartConfirm dlg = new AlertDialogDeviceRestartConfirm(BaseForm.curActivity(), true);
        dlg.setPositiveButton("确定", yesClick);
        dlg.setNegativeButton("取消", noClick);
    }

 

// 判断如果当前已经弹窗了,就不再弹窗。弹窗消失(dismiss)后,ShowDeviceRestartConfirm 重置为false。
                        if (!AlertDialogDeviceRestartConfirm.ShowDeviceRestartConfirm) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        MessageBoxDeviceRestartConfirm(null, null);
                                    } catch (Exception e) {
                                    }
                                }
                            });
                        }

设置弹窗的位置:
int matchParent = ViewGroup.LayoutParams.MATCH_PARENT;//父布局的宽度
params.x = matchParent;
params.y = getResources().getDimensionPixelSize(R.dimen.alert_marginTop);// 距离顶部距离
参考:https://blog.csdn.net/willba/article/details/92613902
https://zhuanlan.zhihu.com/p/619213902?utm_id=0
自定义宽高:https://www.cnblogs.com/buqzl/p/9830556.html

posted on 2023-07-21 13:49  邢帅杰  阅读(466)  评论(0)    收藏  举报