倒计时控件

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 倒计时控件
 */
public class TimerTextView extends TextView implements Runnable{

    private Context mContext;

    public TimerTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
    }

    private long  mhour, mmin, msecond;//天,小时,分钟,秒
    private boolean run=false; //是否启动了

    public void setTimes(long[] times) {
        mhour = times[0];
        mmin = times[1];
        msecond = times[2];

    }

    /**
     * 倒计时计算
     */
    private void ComputeTime() {
        msecond--;
        if (msecond < 0) {
            mmin--;
            msecond = 59;
            if (mmin < 0) {
                mmin = 59;
                mhour--;
                if (mhour < 0) {
                    // 倒计时结束,一天有24个小时
                    mhour = 23;
                }
            }
        }
        if (mhour == 0 && mmin == 0 && msecond == 0){
            Toast.makeText(mContext,"时间到了",Toast.LENGTH_SHORT).show();
            run = false;
        }

    }

    public boolean isRun() {
        return run;
    }

    public void beginRun() {
        this.run = true;
        if (mhour == 0 && mmin == 0 && msecond == 0){
            Toast.makeText(mContext,"",Toast.LENGTH_SHORT).show();
            return;
        }
        run();
    }

    public void stopRun(){
        this.run = false;
    }


    @Override
    public void run() {
        //标示已经启动
        if(run){
            ComputeTime();
            String strTime=(mhour<10?"0"+mhour:mhour)+":"+ (mmin<10?"0"+mmin:mmin)+":"+(msecond<10?"0"+msecond:msecond);
            this.setText(strTime);

            postDelayed(this, 1000);
        }else {
            Log.i("removecallbacks","over");
            removeCallbacks(this);
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值