百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

AndroidStudio_android通过自定义来实现倒计时的AlertDialog

bigegpt 2024-08-21 12:01 2 浏览

截图,还是蛮漂亮的,当然大家可以按照自己的需求,去自己定义效果.

1.首先看一下:PromptDialog类,这个类中有些修改的地方,可以复制直接使用 ,当然也可以根据需要,去掉,倒计时的功能.

package com.baidu.idl.main.facesdk.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.idl.main.facesdk.gatelibrary.R;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.locks.ReentrantLock;


/**
 * 创建时间:2017/9/13.
 * 编写人:zhangr
 * 功能描述:
 */

public class PromptDialog {
    private  AlertDialog dialog;
    private  Activity parent_content;
    private  String parent_title;
    //private static TimerTask task;
    private  int countTime=0;
    private  Timer timer =null;
    private  TextView mTitle;
    public  boolean timerExited =false;
    private ReentrantLock currentLock = new ReentrantLock();

    public interface AlertDialogBtnClickListener {
        //确定
        void clickNext1();

        //否
        void clickNext2();

        //关闭
        void closeListener();
    }

    //设置标题
//    public static void setTitle(Activity content,String title){
//        parent_content =content;
//        parent_title=title;
//        Message msg = new Message();
//        msg.what = 199;
//        handler.sendMessage(msg);
//    }

//    private static Handler handler = new Handler()
//    {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what)
//            {
//                case 199:
//                    View view = LayoutInflater.from(parent_content).inflate(R.layout.dialog_confrim, null);
//                    TextView mTitle = view.findViewById(R.id.dialog_title);
//                    //TextView dialog_confirm_bt = view.findViewById(R.id.dialog_confirm_bt);
//                    //TextView dialog_cancel_bt = view.findViewById(R.id.dialog_cancel_bt);
//                    mTitle.setText(parent_title);
//                    dialog.setTitle(parent_title);
//                    dialog.setMessage(parent_title);
//                    break;
//            }
//        }
//    };

   private  TimerTask task = new TimerTask() {
        @Override
        public void run() {

            /**
             *要执行的操作
             */
            //finish();
            // startActivity(new Intent(mContext, HomeActivity.class));
            //countTime[0] =30;
            //PromptDialog.setTitle(FaceBodyCheckActivity.this,countTime[0] +"秒后退出测量?");
            //normalDialog.setMessage(countTime[0] +"秒后退出测量?");
            currentLock.lock();

            try{
                mTitle.setText(countTime +"秒后退出测量?");
            }catch (Exception e) {
                e.printStackTrace();;
            }

            countTime = countTime - 1;

            if(countTime<=0){
                // 实现页面跳转
                //commLock.lock();
                //logOutFrame();
                //commLock.unlock();
                timerExited =true;
                timer.cancel();
                //finish();
//                            new Handler(new Handler.Callback() {
//                                @Override
//                                public boolean handleMessage(Message msg) {
//                                    // 实现页面跳转
//                                    logOutFrame();
//                                    finish();
//                                    return  true;
//                                }
//                            }).sendEmptyMessageDelayed(0, 2000); //3秒以后,发送空消息
            }

            currentLock.unlock();
        }
    };



    public  void showConfirm(Activity content, String title, final AlertDialogBtnClickListener confirm) {
        //1.首先销毁上次的对话框
        if(dialog!=null){
            dialog.dismiss();
        }

        //int[] position = new int[2];
        View view = LayoutInflater.from(content).inflate(R.layout.dialog_confrim, null);
        mTitle = view.findViewById(R.id.dialog_title);
        TextView dialog_confirm_bt = view.findViewById(R.id.dialog_confirm_bt);
        TextView dialog_cancel_bt = view.findViewById(R.id.dialog_cancel_bt);
        mTitle.setText(title);

        //设定倒计时时间
        timerExited =false;
        countTime = 30;
        timer = new Timer();

        AlertDialog.Builder builder = new AlertDialog.Builder(content);
        builder.setView(view);
        builder.setCancelable(true);   //返回键dismiss

        //创建对话框
        //final AlertDialog dialog = builder.create();
        dialog = builder.create();
        dialog.setCancelable(false);

        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false; //默认返回 false
                }
            }
        });

        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);//去掉圆角背景背后的棱角
//        dialog.setCanceledOnTouchOutside(cancelableTouchOut);   //失去焦点dismiss
        dialog_confirm_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                confirm.clickNext1();
            }
        });
        dialog_cancel_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                confirm.clickNext2();
            }
        });

        WindowManager.LayoutParams wlp =dialog.getWindow().getAttributes();
        wlp.gravity = Gravity.TOP | Gravity.LEFT;
        wlp.x=460;
        wlp.y=150;

        try{
            dialog.show();
        }catch (Exception e){
            e.printStackTrace();
        }

        dialog.getWindow().setLayout(1000,1000);
        timer.schedule(task, 1000,1000);

//        Window window = builder.getWindow();
//        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
//        window.setContentView(R.layout.alertdialog);

    }

    public static void showNext(Activity content, String title, final AlertDialogBtnClickListener next1Listener) {
        View view = LayoutInflater.from(content).inflate(R.layout.dialog_next, null);
        TextView mTitle = view.findViewById(R.id.dialog_title);
        TextView dialog_next1_bt = view.findViewById(R.id.dialog_next1_bt);
        TextView dialog_next2_bt = view.findViewById(R.id.dialog_next2_bt);
        ImageView dialog_close = view.findViewById(R.id.dialog_close);
        mTitle.setText(title);

        AlertDialog.Builder builder = new AlertDialog.Builder(content);
        builder.setView(view);
        builder.setCancelable(true);   //返回键dismiss
        //创建对话框
        final AlertDialog dialog = builder.create();
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);//去掉圆角背景背后的棱角
        dialog.setCancelable(false);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false; //默认返回 false
                }
            }
        });
//        dialog.setCanceledOnTouchOutside(cancelableTouchOut);   //失去焦点dismiss
        dialog_next1_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                next1Listener.clickNext1();
            }
        });
        dialog_next2_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                next1Listener.clickNext2();
            }
        });
        dialog_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                next1Listener.closeListener();
            }
        });
        dialog.setCancelable(false);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false; //默认返回 false
                }
            }
        });

        dialog.show();
    }
}

2.然后我们去看看这里面使用到的一些配置文件和图片等资源

用到的xml界面文件是这个:

D:\YdFaceApp\gatelibrary\src\main\res\layout\dialog_confrim.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/dialog_loading_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/x30"
        android:background="@drawable/bg_bai_r4"
        android:orientation="vertical">

        <TextView
            android:id="@+id/dialog_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:paddingTop="@dimen/x40"
            android:paddingBottom="@dimen/x40"
            android:text="确定退出测量?"
            android:textColor="@color/hei"
            android:textSize="@dimen/x16">

        </TextView>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="@color/hui">

        </TextView>

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

            <TextView
                android:id="@+id/dialog_confirm_bt"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:padding="@dimen/x20"
                android:text="确定"
                android:textColor="@color/main_select"
                android:textSize="@dimen/x16">

            </TextView>

            <TextView
                android:layout_width="0.5dp"
                android:layout_height="match_parent"
                android:layout_marginTop="5dp"
                android:layout_marginBottom="5dp"
                android:background="@color/hui"
                tools:ignore="Suspicious0dp"></TextView>

            <TextView
                android:id="@+id/dialog_cancel_bt"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:padding="@dimen/x20"
                android:text="取消"
                android:textSize="@dimen/x16">

            </TextView>
        </LinearLayout>
    </LinearLayout>


</LinearLayout>

3.然后里面使用到的一些dimen

D:\YdFaceApp\gatelibrary\src\main\res\values\lay_x.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <dimen name="x10">10dp</dimen>
    <dimen name="x12">12dp</dimen>
    <dimen name="x14">14dp</dimen>
    <dimen name="x16">16dp</dimen>
    <dimen name="x18">18dp</dimen>
    <dimen name="x20">20dp</dimen>
    <dimen name="x22">22dp</dimen>
    <dimen name="x24">24dp</dimen>
    <dimen name="x26">26dp</dimen>
    <dimen name="x28">28dp</dimen>
    <dimen name="x30">30dp</dimen>
    <dimen name="x40">40dp</dimen>
    <dimen name="x50">50dp</dimen>
    <dimen name="x60">60dp</dimen>
    <dimen name="x70">70dp</dimen>
    <dimen name="x80">80dp</dimen>
</resources>

4.然后使用到的颜色文件

D:\YdFaceApp\gatelibrary\src\main\res\values\colors.xml 可能有些用不到的,到时候复制过去,删除就可以了.

<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2018 Baidu, Inc. All Rights Reserved.
  -->
<resources>
    <color name="pay_bg">#f2f2f2</color>
    <color name="login_bg">#f4f7fa</color>
    <color name="login_edit_bg">#eeeeee</color>
    <color name="login_submit">#19aa8d</color>
    <color name="hei6">#666666</color>
    <color name="hui">#eeeeee</color>
    <color name="hui_48">#484848</color>
    <color name="white_blue">#b8f7e0</color>
</resources>

5.然后使用到的

@drawable/bg_bai_r4 这个自定义的图形

D:\YdFaceApp\gatelibrary\src\main\res\drawable\bg_bai_r4.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
            <!-- 圆角的半径 -->
            <corners android:radius="15dp" />
        </shape>
    </item>
</layer-list>

6.然后需要的

R.id.dialog_confirm_bt
R.id.dialog_cancel_bt

在 D:\YdFaceApp\gatelibrary\src\main\res\layout\dialog_confrim.xml 文件中已经有了,然后我们去看,如何使用这个alertDialog去.

7.可以看到下面就是使用的过程了

 //1.这里是采用自己设计的dialog画面来进行
                final boolean[] isNeedExit = {true};
                final Integer[] countTime = {32};
                final boolean isBooleanExit = false;
                final Timer timer = new Timer();
                final PromptDialog promptDialog =new PromptDialog();

                final TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        /**
                         *要执行的操作
                         */
                        countTime[0] = countTime[0] - 1;
                        if(countTime[0]<=0){
                            if(promptDialog.timerExited){ // 通过这个promptDialog.timerExited可以判断,promptDialog内部的倒计时timer是否已经倒计时结束
                                // 实现页面跳转
                                .....要执行的业务逻辑
                                timer.cancel();
                                finish();
                            }
                        }
                    }
                };

                new Handler(new Handler.Callback() {
                    @Override
                    public boolean handleMessage(Message msg) {
                        try{
                            //实现页面跳转
                            promptDialog.showConfirm(FaceBodyCheckActivity.this, "确定退出测量?", new PromptDialog.AlertDialogBtnClickListener() {
                                @Override
                                public void clickNext1() {
                                    //确定按钮
                                    new Handler(new Handler.Callback() {
                                        @Override
                                        public boolean handleMessage(Message msg) {
                                            Toast.makeText(FaceBodyCheckActivity.this,"3秒后退出测量",Toast.LENGTH_LONG).show();
                                            //3.3秒以后调用退出接口
                                            isNeedExit[0] =false;

                                            new Handler(new Handler.Callback() {
                                                @Override
                                                public boolean handleMessage(Message msg) {
                                                    // 实现页面跳转
                                                    //下面是要实现的业务逻辑
                                                    commLock.lock();
                                                    logOutFrame();
                                                    commLock.unlock();
                                                    timer.cancel();
                                                    finish();
                                                    return  true;
                                                }
                                            }).sendEmptyMessageDelayed(0, 4000); //3秒以后,发送空消息

                                            return  true;
                                        }
                                    }).sendEmptyMessageDelayed(0, 600); //3秒以后,发送空消息
                                }

                                @Override
                                public void clickNext2() {
                                    //取消按钮
                                    isNeedExit[0] =false;
                                    timer.cancel();
                                }

                                @Override
                                public void closeListener() {
                                    //关闭按钮

                                }
                            });

                            //这里就是判断,当第一次进来的时候,先去开启timer,进行倒计时
                            //开启timer,注意在PromptDialog中也有一个timer,那个timer
                            //是用来显示倒计时用的.

                            if(isNeedExit[0]){
                                timer.schedule(task, 1000,1000);
                            }

                        }catch (Exception e){
                            e.printStackTrace();
                        }

                        return  true;
                    }
                }).sendEmptyMessageDelayed(0, 4000); //3秒以后,发送空消息

去看看代码,应该就能明白了,不过我还是要解释一下:

在PromptDialog中有个timer,我们可以在里面写上,需要显示倒计时多长时间,他就会自动倒计时了,然后

在PromptDialog中还有一个变量timerExited,如果PromptDialog中的那个timer倒计时完了,到0了,那么

它里面的这个PromptDialog,就把timerExited设置为true,表示已经倒计时结束.


然后可以看到使用这个PromptDialog的时候,同样我也用了一个timer倒计时,等这个倒计时完了以后,

我会去判断PromptDialog中的那个timerExited是不是true了,如果是true,表示promptDialog的timer也倒计时完了

这个时候,我就可以做业务处理, 比如倒计时结束后是自动退出界面啊...还是怎么样,上面是自动退出界面.

相关推荐

悠悠万事,吃饭为大(悠悠万事吃饭为大,什么意思)

新媒体编辑:杜岷赵蕾初审:程秀娟审核:汤小俊审签:周星...

高铁扒门事件升级版!婚宴上‘冲喜’老人团:我们抢的是社会资源

凌晨两点改方案时,突然收到婚庆团队发来的视频——胶东某酒店宴会厅,三个穿大红棉袄的中年妇女跟敢死队似的往前冲,眼瞅着就要扑到新娘的高额钻石项链上。要不是门口小伙及时阻拦,这婚礼造型团队熬了三个月的方案...

微服务架构实战:商家管理后台与sso设计,SSO客户端设计

SSO客户端设计下面通过模块merchant-security对SSO客户端安全认证部分的实现进行封装,以便各个接入SSO的客户端应用进行引用。安全认证的项目管理配置SSO客户端安全认证的项目管理使...

还在为 Spring Boot 配置类加载机制困惑?一文为你彻底解惑

在当今微服务架构盛行、项目复杂度不断攀升的开发环境下,SpringBoot作为Java后端开发的主流框架,无疑是我们手中的得力武器。然而,当我们在享受其自动配置带来的便捷时,是否曾被配置类加载...

Seata源码—6.Seata AT模式的数据源代理二

大纲1.Seata的Resource资源接口源码2.Seata数据源连接池代理的实现源码3.Client向Server发起注册RM的源码4.Client向Server注册RM时的交互源码5.数据源连接...

30分钟了解K8S(30分钟了解微积分)

微服务演进方向o面向分布式设计(Distribution):容器、微服务、API驱动的开发;o面向配置设计(Configuration):一个镜像,多个环境配置;o面向韧性设计(Resista...

SpringBoot条件化配置(@Conditional)全面解析与实战指南

一、条件化配置基础概念1.1什么是条件化配置条件化配置是Spring框架提供的一种基于特定条件来决定是否注册Bean或加载配置的机制。在SpringBoot中,这一机制通过@Conditional...

一招解决所有依赖冲突(克服依赖)

背景介绍最近遇到了这样一个问题,我们有一个jar包common-tool,作为基础工具包,被各个项目在引用。突然某一天发现日志很多报错。一看是NoSuchMethodError,意思是Dis...

你读过Mybatis的源码?说说它用到了几种设计模式

学习设计模式时,很多人都有类似的困扰——明明概念背得滚瓜烂熟,一到写代码就完全想不起来怎么用。就像学了一堆游泳技巧,却从没下过水实践,很难真正掌握。其实理解一个知识点,就像看立体模型,单角度观察总...

golang对接阿里云私有Bucket上传图片、授权访问图片

1、为什么要设置私有bucket公共读写:互联网上任何用户都可以对该Bucket内的文件进行访问,并且向该Bucket写入数据。这有可能造成您数据的外泄以及费用激增,若被人恶意写入违法信息还可...

spring中的资源的加载(spring加载原理)

最近在网上看到有人问@ContextConfiguration("classpath:/bean.xml")中除了classpath这种还有其他的写法么,看他的意思是想从本地文件...

Android资源使用(android资源文件)

Android资源管理机制在Android的开发中,需要使用到各式各样的资源,这些资源往往是一些静态资源,比如位图,颜色,布局定义,用户界面使用到的字符串,动画等。这些资源统统放在项目的res/独立子...

如何深度理解mybatis?(如何深度理解康乐服务质量管理的5个维度)

深度自定义mybatis回顾mybatis的操作的核心步骤编写核心类SqlSessionFacotryBuild进行解析配置文件深度分析解析SqlSessionFacotryBuild干的核心工作编写...

@Autowired与@Resource原理知识点详解

springIOCAOP的不多做赘述了,说下IOC:SpringIOC解决的是对象管理和对象依赖的问题,IOC容器可以理解为一个对象工厂,我们都把该对象交给工厂,工厂管理这些对象的创建以及依赖关系...

java的redis连接工具篇(java redis client)

在Java里,有不少用于连接Redis的工具,下面为你介绍一些主流的工具及其特点:JedisJedis是Redis官方推荐的Java连接工具,它提供了全面的Redis命令支持,且...