Android 倒计时按钮的实现

来源:互联网 发布:淘宝店铺收藏链接生成 编辑:程序博客网 时间:2024/05/19 14:00

Android中获取验证码之类的地方很多,这类地方一般都会用到倒计时按钮,点击按钮之后,开始倒计时,时间到了之后再能重新发送。

下面用Android自带的CountDownTimer可以很简单的就实现:

页面布局,一个简单的按钮

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    >    <Button        android:layout_centerHorizontal="true"        android:id="@+id/send"        android:layout_width="100dp"        android:text="点我"        android:layout_height="wrap_content"/></RelativeLayout>

初始化CountDownTimer,

CountDownTimer mCountDownTimer = new CountDownTimer(60 * 1000, 1000) {            @Override            public void onTick(long l) {                mIsRunning = true;                mBtn_ok.setText("还有"+(l / 1000) + "秒");            }            @Override            public void onFinish() {                mIsRunning = false;                mBtn_ok.setText("重新发送");            }        };

onTick()是点击之后,执行的,onFinish()是倒计时结束后执行的。mIsRunning是为了标志一下是否正在倒计时。

在按钮的点击事件触发后调用CountDownTimer的start()方法

    @Override    public void onClick(View view) {        if (!mIsRunning) {            mCountDownTimer.start();        }            }

效果图:


0 0