当前位置: 首页 > 最新文章 > 正文

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

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

admin

"); currentLock.lock(); try{ mTitle.setText(countTime +"秒后退出测量?"); }catch { e.printStackTrace();; } countTime = countTime - 1; if{ // 实现页面跳转 //commLock.lock(); //logOutFrame();

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

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

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

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();    }}
AndroidStudio_android通过自定义来实现倒计时的AlertDialog

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>
AndroidStudio_android通过自定义来实现倒计时的AlertDialog

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>
AndroidStudio_android通过自定义来实现倒计时的AlertDialog

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>
AndroidStudio_android通过自定义来实现倒计时的AlertDialog

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>
AndroidStudio_android通过自定义来实现倒计时的AlertDialog

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秒以后,发送空消息
AndroidStudio_android通过自定义来实现倒计时的AlertDialog

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

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

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

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


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

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

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


上一篇: java堆、栈、堆栈,常量池的区别 下一篇:学习编程第181天 python编程列表框listbox控件增删查
返回顶部