项目中用到的,防止以后忘记了,先留着
demo下载地址 http://download.csdn.net/detail/dl10210950/9646940
<span style="font-size:18px;">package com.duanlian.countdowndemo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private Timer mTimer = null;
private TextView send_tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send_tv = (TextView) findViewById(R.id.time);
//点击事件
send_tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startTimer();
}
});
}
//开始倒计时
private void startTimer() {
//点击获取验证码后改变按钮的状态,让按钮不可点击
send_tv.setClickable(false);
if (mTimer == null) {
mTimer = new Timer(true);
}
mTimer.schedule(new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(1);
}
}, 0, 1000);
}
private int countdown = 60;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
send_tv.setText(countdown + "秒");
send_tv.setAlpha(0.5f);
if (0 == countdown) {
//停止倒计时显示页面
resume();
stopTimer();
return;
}
countdown--;
}
};
private void resume() {
stopTimer();
countdown = 60;
//倒计时结束后,让按钮重新可点击
send_tv.setClickable(true);
send_tv.setText("重发");
send_tv.setAlpha(0.9f);
}
private void stopTimer() {
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
}
}
</span>
<?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"
tools:context="com.duanlian.countdowndemo.MainActivity">
<TextView
android:id="@+id/time"
android:background="#ff00ff"
android:layout_width="60dp"
android:layout_height="60dp"
android:gravity="center"
android:textSize="20dp"
android:text="开始"/>
</RelativeLayout>