欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android自定义TimeButton实现倒计时按钮

程序员文章站 2022-11-19 16:56:36
项目需要要实现一个带有倒计时功能的按钮,其效果类似发送验证码之后在按钮上显示倒计时并且将按钮设置为不可用的功能。 为了项目中其他地方能够调用到,便重写了一个继承于button的tim...

项目需要要实现一个带有倒计时功能的按钮,其效果类似发送验证码之后在按钮上显示倒计时并且将按钮设置为不可用的功能。

为了项目中其他地方能够调用到,便重写了一个继承于button的timebutton来实现倒计时功能,并方便调用。

老规矩,上效果图:

Android自定义TimeButton实现倒计时按钮

逻辑也不复杂,直接上代码:

首先新建一个app.class继承于application

package com.example.xuboyu.myapplication;
 
/**
 * 用于存放倒计时时间
 * @author bnuzlbs-xuboyu 2017/4/5.
 */
import java.util.map;
 
import android.app.application;
 
public class app extends application {
 // 用于存放倒计时时间
 public static map<string, long> map;
}

然后编写timebutton.class继承于button

package com.example.xuboyu.myapplication;
 
 
import java.util.hashmap;
import java.util.map;
import java.util.timer;
import java.util.timertask;
 
import android.annotation.suppresslint;
import android.content.context;
import android.os.bundle;
import android.os.handler;
import android.util.attributeset;
import android.util.log;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.button;
 
/**
 * 倒计时按钮
 * @author bnuzlbs-xuboyu 2017/4/5.
 * 注意把该类的oncreate()ondestroy()和activity的oncreate()ondestroy()同步处理
 */
public class timebutton extends button implements onclicklistener {
 private long lenght = 60 * 1000;// 倒计时长度,这里给了默认60秒
 private string textafter = "秒后重新获取~";
 private string textbefore = "点击获取验证码~";
 private int colorafter;
 private int colorbefore;
 private final string time = "time";
 private final string ctime = "ctime";
 private onclicklistener monclicklistener;
 private timer t;
 private timertask tt;
 private long time;
 map<string, long> map = new hashmap<string, long>();
 
 public timebutton(context context) {
 super(context);
 setonclicklistener(this);
 
 }
 
 public timebutton(context context, attributeset attrs) {
 super(context, attrs);
 setonclicklistener(this);
 }
 
 @suppresslint("handlerleak")
 handler han = new handler() {
 public void handlemessage(android.os.message msg) {
  timebutton.this.settext(time / 1000 + textafter);
  time -= 1000;
  if (time < 0) {
  timebutton.this.setenabled(true);
  timebutton.this.settext(textbefore);
  cleartimer();
  }
 };
 };
 
 private void inittimer() {
 time = lenght;
 t = new timer();
 tt = new timertask() {
 
  @override
  public void run() {
  log.e("xuboyu", time / 1000 + "");
  han.sendemptymessage(0x01);//十六进制的数字1
  }
 };
 }
 
 private void cleartimer() {
 if (tt != null) {
  tt.cancel();
  tt = null;
 }
 if (t != null)
  t.cancel();
 t = null;
 }
 
 @override
 public void setonclicklistener(onclicklistener l) {
 if (l instanceof timebutton) {
  super.setonclicklistener(l);
 } else
  this.monclicklistener = l;
 }
 
 @override
 public void onclick(view v) {
 if (monclicklistener != null)
  monclicklistener.onclick(v);
 inittimer();
 this.settext(time / 1000 + textafter);
 this.setenabled(false);
 t.schedule(tt, 0, 1000);
 // t.scheduleatfixedrate(task, delay, period);
 }
 
 /**
 * 和activity的ondestroy()方法同步
 */
 public void ondestroy() {
 if (app.map == null)
  app.map = new hashmap<string, long>();
 app.map.put(time, time);
 app.map.put(ctime, system.currenttimemillis());
 cleartimer();
 log.e("xuboyu", "ondestroy");
 }
 
 /**
 * 和activity的oncreate()方法同步
 */
 public void oncreate(bundle bundle) {
 log.e("xuboyu:倒计时相关", app.map + "");
 if (app.map == null)
  return;
 if (app.map.size() <= 0)// 这里表示没有上次未完成的计时
  return;
 long time = system.currenttimemillis() - app.map.get(ctime)
  - app.map.get(time);
 app.map.clear();
 if (time > 0)
  return;
 else {
  inittimer();
  this.time = math.abs(time);
  t.schedule(tt, 0, 1000);
  this.settext(time + textafter);
  this.setenabled(false);
 }
 }
 
 /** * 设置计时时候显示的文本 */
 public timebutton settextafter(string text1) {
 this.textafter = text1;
 return this;
 }
 
 /** * 设置点击之前的文本 */
 public timebutton settextbefore(string text0) {
 this.textbefore = text0;
 this.settext(textbefore);
 return this;
 }
 
 /**
 * 设置到计时长度
 * @param lenght
 * 时间 默认毫秒
 * @return
 */
 public timebutton setlenght(long lenght) {
 this.lenght = lenght;
 return this;
 }
}

最后在mainactivity.class中调用

package com.example.xuboyu.myapplication;
 
import android.app.activity;
import android.os.bundle;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.toast;
 
/**
 * 测试主界面
 * @author bnuzlbs-xuboyu 2017/4/5.
 */
public class mainactivity extends activity implements onclicklistener {
 
 private timebutton v;
 private timebutton v2;
 private timebutton v3;
 
 @override
 protected void oncreate(bundle savedinstancestate) {
 super.oncreate(savedinstancestate);
 setcontentview(r.layout.activity_main);
 v = (timebutton) findviewbyid(r.id.button1);
 v.oncreate(savedinstancestate);
 v.settextafter("秒后重新排队").settextbefore("点击开始排队").setlenght(15 * 1000);
 v.setonclicklistener(this);
 
 v2 = (timebutton) findviewbyid(r.id.button2);
 v2.oncreate(savedinstancestate);
 v2.settextafter("秒后重新验证").settextbefore("点击发送验证码").setlenght(10 * 1000);
 v2.setonclicklistener(this);
 
 v3 = (timebutton) findviewbyid(r.id.button3);
 v3.oncreate(savedinstancestate);
 v3.settextafter("秒后重新倒计时").settextbefore("点击开始倒计时").setlenght(5 * 1000);
 v3.setonclicklistener(this);
 }
 
 @override
 public void onclick(view v) {
 // todo auto-generated method stub
 toast.maketext(mainactivity.this, "这是处理调用者onclicklistnenr",
  toast.length_short).show();
 }
 
 @override
 protected void ondestroy() {
 // todo auto-generated method stub
 v.ondestroy();
 v2.ondestroy();
 super.ondestroy();
 }
}

其中绿色按钮是使用了自定义样式的button,使用起来也很简单

首先在drawable中新建一个样式文件mybutton.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
 <solid android:color="#5cbe6c" />
 
 <!-- 设置按钮的四个角为弧形 -->
 <!-- android:radius 弧形的半径 -->
 <corners android:radius="15dip" />
 
 <!-- padding:button里面的文字与button边界的间隔 -->
 <padding
 android:bottom="10dp"
 android:left="10dp"
 android:right="10dp"
 android:top="10dp" />
</shape>

然后在定义timebutton的时候如下:

android:background="@drawable/mybutton"
<com.example.xuboyu.myapplication.timebutton
 android:id="@+id/button2"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text=""
 android:background="@drawable/mybutton"
 android:layout_margin="20dp"/>

那么定义出来的button样式就为下图:

Android自定义TimeButton实现倒计时按钮

记得在androidmanifest.xml中的application添加:

android:name=".app"
<application
 android:allowbackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 android:supportsrtl="true"
 android:theme="@style/apptheme"
 android:name=".app">
 <activity android:name=".mainactivity" >
  <intent-filter>
  <action android:name="android.intent.action.main" />
 
  <category android:name="android.intent.category.launcher" />
  </intent-filter>
 </activity>
</application>

ps.这个倒计时按钮存在一个问题,对于长时间计时而言,用户可能在计时后退出应用程序,如果用户把我们的app置于后台,那么ok,我们的倒计时还是可以进行,但是假如用户在退出后把app进程滑掉,或者使用了其他软件清理后台等等,就会执行ondestory方法,再次进去app的时候只能重新建立一个timer。所以打算的是使用轻量级存储来储存每次退出后的倒计时数据,然后在重新oncreate的时候为timer赋值。当然对于短时间的计时,即在用户可接受的等待范围内是完全可以接受的!有bug也欢迎指出,对于应用进程被销毁时timer也销毁这个问题假如你有更好的解决方法,也请多指教!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。