本文主要是介绍Android 自定义倒计时的View demo 类似CountDownTimer,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
倒计时要实现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() {@Overridepublic 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
这篇关于Android 自定义倒计时的View demo 类似CountDownTimer的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!