Android 自定义倒计时的View demo 类似CountDownTimer

来源:互联网 发布:mac如何重新安装系统 编辑:程序博客网 时间:2024/05/30 04:58

倒计时要实现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 void setOnCallback(Callback callback){        this.callback=callback;    }    public String[] getLeftTimeFormatedStrings(long leftTime) {        String days = "00";        String hours = "00";        String minutes = "00";        String seconds = "00";        if (leftTime > 0) {            //实际多少秒            long trueSeconds = leftTime / 1000;            //当前的秒            long secondValue = trueSeconds % 60;            if (secondValue < 10) {                seconds = String.valueOf("0" + secondValue);            } else {                seconds = String.valueOf(secondValue);            }            //当前的分            long trueMinutes = trueSeconds / 60;            long minuteValue = trueMinutes % 60;            if (minuteValue < 10) {                minutes = String.valueOf("0" + minuteValue);            } else {                minutes = String.valueOf(minuteValue);            }            //当前的小时数            long trueHours = trueMinutes / 60;            long hourValue = trueHours % 24;            if (hourValue < 10) {                hours = String.valueOf("0" + hourValue);            } else {                hours = String.valueOf(hourValue);            }            //当前的天数            long dayValue = trueHours / 24;            if (dayValue < 10) {                days = String.valueOf("0" + dayValue);            } else {                days = String.valueOf(dayValue);            }        }        return new String[]{days,hours,minutes,seconds};    }}

然后在布局中使用该自定义View
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:orientation="vertical"    tools:context="tech.androidstudio.mycountdowntimer.MainActivity">    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="btnStart"        android:text="开始倒计时25小时"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="btnStartOneMinute"        android:text="开始倒计时1分钟"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="btnStop"        android:text="停止"/><tech.androidstudio.mycountdowntimer.MyCountDownTimerView    android:background="#aa111111"    android:layout_width="match_parent"    android:layout_height="30dp"    android:layout_marginTop="10dp"    android:gravity="center"    android:id="@+id/myCountTime">    <TextView        android:layout_width="30dp"        android:layout_height="wrap_content"        android:textAlignment="center"        android:background="@drawable/shape_time"        android:text="00"/>    <TextView        android:layout_width="30dp"        android:layout_height="wrap_content"        android:text=" 天"/>    <TextView        android:layout_width="30dp"        android:layout_height="wrap_content"        android:textAlignment="center"        android:background="@drawable/shape_time"        android:text="00"/>    <TextView        android:layout_width="30dp"        android:layout_height="wrap_content"        android:text=" 时"/>    <TextView        android:layout_width="30dp"        android:layout_height="wrap_content"        android:textAlignment="center"        android:background="@drawable/shape_time"        android:text="00"/>    <TextView        android:layout_width="30dp"        android:layout_height="wrap_content"        android:text=" 分"/>    <TextView        android:layout_width="30dp"        android:layout_height="wrap_content"        android:textAlignment="center"        android:background="@drawable/shape_time"        android:text="00"/>    <TextView        android:layout_width="30dp"        android:layout_height="wrap_content"        android:text=" 秒"/></tech.androidstudio.mycountdowntimer.MyCountDownTimerView></LinearLayout>

数字的背景使用下面的:shape_time.xml
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"><solid android:color="@android:color/white"></solid>    <stroke android:color="@android:color/holo_red_dark" android:width="2px"></stroke></shape>


然后MainActivity 中如下:
package tech.androidstudio.mycountdowntimer;import android.os.CountDownTimer;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Toast;import java.util.Calendar;public class MainActivity extends AppCompatActivity implements MyCountDownTimerView.Callback {    private MyCountDownTimerView mMycountDownTimerView;    private long leftTime;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        leftTime = 1000*60*60*25*1l;        mMycountDownTimerView = (MyCountDownTimerView)findViewById(R.id.myCountTime);        mMycountDownTimerView.setText(leftTime);        mMycountDownTimerView.setOnCallback(this);    }    @Override    public void onFinish() {        Toast.makeText(this,"结束了",Toast.LENGTH_LONG).show();    }    public void btnStart(View view) {        mMycountDownTimerView.setText(leftTime);        mMycountDownTimerView.start();    }    public void btnStop(View view) {        mMycountDownTimerView.stop();    }    public void btnStartOneMinute(View view) {        mMycountDownTimerView.setText(60*1000l);        mMycountDownTimerView.start();    }}


另一种自定义View的形式,也可以如下:
package com.wbm.app.utils.ui;import android.content.Context;import android.util.AttributeSet;import android.widget.LinearLayout;import android.widget.TextView;/** * Created by drome on 16/6/23. */public class TimeView extends LinearLayout implements Runnable{    private Long time;    private boolean isRun=false;    private CallBack callBack;    public TimeView(Context context) {        super(context);    }    public TimeView(Context context, AttributeSet attrs) {        super(context, attrs);    }    public TimeView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    public void setDate(Long time){        this.time=time;        setText(time);    }    private void setText(Long time){        String[] times=getLeftTimeFormatedStrings(time);        for(int i=0;i<times.length;i++){            ((TextView)getChildAt(i*2+1)).setText(times[i]);        }    }    public synchronized void runTimer(){        if(!isRun){            isRun=true;            post(this);        }    }    public void stopTimer(){        isRun=false;    }    @Override    public void run() {        if(isRun) {            time = time - 1000;            if(time<=0){                isRun=false;                if(callBack!=null){                    callBack.onFinish();                }            }else{                setText(time);                postDelayed(this, 1000);            }        }    }    public void setCallBack(CallBack callBack){        this.callBack=callBack;    }    public interface CallBack{        void onFinish();    }    public String[] getLeftTimeFormatedStrings(long leftTime) {        String days = "00";        String hours = "00";        String minutes = "00";        String seconds = "00";        if (leftTime > 0) {            //实际多少秒            long trueSeconds = leftTime / 1000;            //当前的秒            long secondValue = trueSeconds % 60;            if (secondValue < 10) {                seconds = String.valueOf("0" + secondValue);            } else {                seconds = String.valueOf(secondValue);            }            //当前的分            long trueMinutes = trueSeconds / 60;            long minuteValue = trueMinutes % 60;            if (minuteValue < 10) {                minutes = String.valueOf("0" + minuteValue);            } else {                minutes = String.valueOf(minuteValue);            }            //当前的小时数            long trueHours = trueMinutes / 60;            long hourValue = trueHours % 24;            if (hourValue < 10) {                hours = String.valueOf("0" + hourValue);            } else {                hours = String.valueOf(hourValue);            }            //当前的天数            long dayValue = trueHours / 24;            if (dayValue < 10) {                days = String.valueOf("0" + dayValue);            } else {                days = String.valueOf(dayValue);            }        }        return new String[]{days,hours,minutes,seconds};    }}




0 0
原创粉丝点击