倒计时要实现3个功能:开始,停止以及停止以后的回调。
先上demo效果图
首先自定义一个View叫做
MyCountDownTimerView
package tech.androidstudio.mycountdowntimer; import android.content.Context; import android.os.CountDownTimer; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import java.util.Date; /** * Created by Kodulf on 2016/6/24. */ public class MyCountDownTimerView extends LinearLayout { /** * 首先实现倒计时的功能 */ private long leftTime; private boolean started = false; private Callback callback; public MyCountDownTimerView(Context context) { super(context); } public MyCountDownTimerView(Context context, AttributeSet attrs) { super(context, attrs); } public void setText(long left){ leftTime=left; String[] leftTimeFormatedStrings = getLeftTimeFormatedStrings(leftTime); int childCount = getChildCount(); for (int i = 0; i < childCount/2; i++) { TextView childAt = (TextView) getChildAt(i*2); childAt.setText(leftTimeFormatedStrings[i]); } } public synchronized void start() { if(started==false) { started = true; Message message = new Message(); mHandler.sendEmptyMessage(1); } } private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: if (started == true) { if (leftTime > 1000) { leftTime=leftTime-1000; setText(leftTime); mHandler.sendEmptyMessageDelayed(1, 1000); } else { //回调 callback.onFinish(); } } break; case 2: leftTime=0l; started=false; setText(0l); break; } } }; public synchronized void stop(){ mHandler.sendEmptyMessage(2); } public interface Callback{ void onFinish(); } public