package com.loaderman.countdowntimerdemo;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView tvTime; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTime = (TextView) findViewById(R.id.tv_time);
tvTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new countDownTimer<TextView>(tvTime);
}
});
}
public class countDownTimer<T> extends CountDownTimer {
private TextView mTextView; public countDownTimer(T text) {
super(60000,1000);
this.mTextView = ((TextView)text);
mTextView.setClickable(false);
start();
} /**
* start后开始执行的方法,按照间隔时间执行一次
* @param millisUntilFinished
*/
@Override
public void onTick(long millisUntilFinished) {
mTextView.setText(String.format("%s秒",millisUntilFinished/1000));
} /**
* 时间结束时调用的方法
*/
@Override
public void onFinish() {
mTextView.setText("获取验证码");
mTextView.setClickable(true);
}
}
}
<?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"
android:gravity="center"
tools:context="com.loaderman.countdowntimerdemo.MainActivity">
<TextView
android:textColor="#F00"
android:textSize="18sp"
android:id="@+id/tv_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始倒计时"/>
</RelativeLayout>

效果图:

利用CountDownTimer倒计时的简单使用实现-LMLPHP

05-11 21:41