Android自定義TimeButton實現(xiàn)倒計時按鈕
項目需要要實現(xiàn)一個帶有倒計時功能的按鈕,其效果類似發(fā)送驗證碼之后在按鈕上顯示倒計時并且將按鈕設(shè)置為不可用的功能。
為了項目中其他地方能夠調(diào)用到,便重寫了一個繼承于Button的TimeButton來實現(xiàn)倒計時功能,并方便調(diào)用。
老規(guī)矩,上效果圖:

邏輯也不復(fù)雜,直接上代碼:
首先新建一個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;// 倒計時長度,這里給了默認(rèn)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);//十六進(jìn)制的數(shù)字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:倒計時相關(guān)", 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);
}
}
/** * 設(shè)置計時時候顯示的文本 */
public TimeButton setTextAfter(String text1) {
this.textafter = text1;
return this;
}
/** * 設(shè)置點擊之前的文本 */
public TimeButton setTextBefore(String text0) {
this.textbefore = text0;
this.setText(textbefore);
return this;
}
/**
* 設(shè)置到計時長度
* @param lenght
* 時間 默認(rèn)毫秒
* @return
*/
public TimeButton setLenght(long lenght) {
this.lenght = lenght;
return this;
}
}
最后在MainActivity.class中調(diào)用
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("點擊發(fā)送驗證碼").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, "這是處理調(diào)用者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" /> <!-- 設(shè)置按鈕的四個角為弧形 --> <!-- 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樣式就為下圖:

記得在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.這個倒計時按鈕存在一個問題,對于長時間計時而言,用戶可能在計時后退出應(yīng)用程序,如果用戶把我們的APP置于后臺,那么OK,我們的倒計時還是可以進(jìn)行,但是假如用戶在退出后把APP進(jìn)程滑掉,或者使用了其他軟件清理后臺等等,就會執(zhí)行OnDestory方法,再次進(jìn)去APP的時候只能重新建立一個Timer。所以打算的是使用輕量級存儲來儲存每次退出后的倒計時數(shù)據(jù),然后在重新OnCreate的時候為Timer賦值。當(dāng)然對于短時間的計時,即在用戶可接受的等待范圍內(nèi)是完全可以接受的!有Bug也歡迎指出,對于應(yīng)用進(jìn)程被銷毀時Timer也銷毀這個問題假如你有更好的解決方法,也請多指教!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android使用Kotlin API實踐WorkManager
- 使用Android studio3.6的java api方式調(diào)用opencv
- Android 通過API獲取數(shù)據(jù)庫中的圖片文件方式
- Android 中TeaPickerView數(shù)據(jù)級聯(lián)選擇器功能的實例代碼
- Android音視頻之視頻采集(系統(tǒng)API預(yù)覽)
- Android CountDownTimer案例總結(jié)
- Android日歷控件PickTime代碼實例
- Android倒計時神器(CountDownTimer)
- Android中各種Time API詳細(xì)
相關(guān)文章
Android使用HorizontalScrollView實現(xiàn)水平滾動
這篇文章主要為大家詳細(xì)介紹了Android使用HorizontalScrollView實現(xiàn)水平滾動,并點擊有相應(yīng)的反應(yīng)效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-11-11
Android實現(xiàn)計時與倒計時的常用方法小結(jié)
這篇文章主要介紹了Android實現(xiàn)計時與倒計時的常用方法,總結(jié)并對比分析了幾種常用計時方法的特點,具有一定參考借鑒價值,需要的朋友可以參考下2015-10-10
Android自定義View實現(xiàn)仿1號店垂直滾動廣告條代碼
這篇文章主要介紹了Android自定義View實現(xiàn)仿1號店垂直滾動廣告條代碼,實現(xiàn)步驟及實現(xiàn)原理本文給大家介紹的非常詳細(xì),需要的朋友參考下吧2017-01-01
Eclipse打開時“發(fā)現(xiàn)了以元素''d:skin''”開頭的無效內(nèi)容。此處不應(yīng)含有子元素的解決方法
這篇文章主要介紹了Eclipse打開時“發(fā)現(xiàn)了以元素'd:skin'”開頭的無效內(nèi)容。此處不應(yīng)含有子元素的解決方法,涉及Android sdk中devices.xml文件的修改,需要的朋友可以參考下2016-01-01
Android中判斷網(wǎng)絡(luò)是否可用的代碼分享
這篇文章主要介紹了Android中判斷網(wǎng)絡(luò)是否可用的代碼分享,本文直接給出實現(xiàn)代碼,需要的朋友可以參考下2015-03-03

