概要
能上图就别BB,看右上角的效果。
一、其实就是个TextView
import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
public class TimerView extends TextView {
private static String TAG = TimerView.class.getSimpleName();
private static int totalTime = 20; // 默认20S倒计时
private IOnTimerEventListener onTimerEventListener;
private CountDownTimer countDownTimer = null;
public void setOnTimerEventListener(IOnTimerEventListener onTimerEventListener) {
this.onTimerEventListener = onTimerEventListener;
}
public TimerView(Context context) {
super(context);
}
public TimerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TimerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public TimerView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void setTotalTime(int totalTime){
this.totalTime = totalTime;
this.setText(String.valueOf(totalTime));
}
/**
* 开始倒计时
*/
public void startTimer(){
if(countDownTimer == null){
countDownTimer = new CountDownTimer(totalTime * 1000, 1 * 1000) {
@Override
public void onTick(long millisUntilFinished) { // 这个是每次间隔指定时间的回调
// 这里可以更新UI
TimerView.this.setText("" + millisUntilFinished / 1000);
}
@Override
public void onFinish() { // 这个是倒计时结束的回调
TimerView.this.setText("" + 0);
cancel();
if(onTimerEventListener != null){
onTimerEventListener.onTimerEvent();
}
}
};
countDownTimer.start();
}
}
/**
* 结束倒计时
*/
public void stopTimer(){
if(countDownTimer != null){
countDownTimer.cancel();
}
}
/**
* 倒计时结束的响应事件
*/
public interface IOnTimerEventListener{
public void onTimerEvent();
}
}
二、布局中是这么用的
<com.hisign.id_verification.viewsupport.TimerView
android:id="@+id/tvTimer"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginTop="50dp"
android:layout_marginRight="50dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:gravity="center"
android:text="60"
android:textColor="@color/black"
android:textSize="25sp"
android:background="@drawable/shape_text_timer"/>
shape_text_timer.xml:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
android:useLevel="false">
<solid android:color="@color/white"/>
<stroke
android:width="1dp"
android:color="@color/white"/>
<size android:width="20dp"
android:height="20dp"/>
</shape>
三、代码中是这么用滴
@BindView(R.id.tvTimer)
TimerView tvTimer;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_takephoto);
ButterKnife.bind(this);
tvTimer.setTotalTime(Integer.parseInt(time));
tvTimer.startTimer();
tvTimer.setOnTimerEventListener(new TimerView.IOnTimerEventListener() {
@Override
public void onTimerEvent() {
ActivityJump.go2Main(TakePhotoActivity.this);
TakePhotoActivity.this.finish();
}
});
}