最近在做直播相关的项目。今天实现了一个小功能。倒计时操作。并在倒计时结束时执行自己想要的操作。
1. 调用方法:
TextView mTime = (TextView)view.findViewById(R.id.btn_time);
MyCountTimer myCountTimer = new MyCountTimer(4000, 1000, mTime, "重新倒计时") {
@Override
public void onFinish() {
UIUtils.showToast("倒计时结束了!");
//可以执行你想要的操作了。
}
};
2.布局文件。
<TextView
android:id="@+id/btn_time"
android:layout_width="@dimen/base160dp"
android:layout_height="@dimen/base36dp"
android:layout_marginTop="@dimen/base50dp"
android:gravity="center"
android:layout_centerInParent="true"
android:text="倒计时"
android:textColor="@color/black"
android:textSize="17sp" />
3.工具类代码: CountDownTimer 类 的使用。
public abstract class MyCountTimer extends CountDownTimer {
public static final int TIME_COUNT = 31000;//倒计时总时间为31S,时间防止从29s开始显示(以倒计时30s为例子)
private TextView btn;
private String endStrRid;
/**
* 参数 millisInFuture 倒计时总时间(如30s,60S,120s等)
* 参数 countDownInterval 渐变时间(每次倒计1s)
* 参数 btn 点击的按钮(因为Button是TextView子类,为了通用我的参数设置为TextView)
* 参数 endStrRid 倒计时结束后,按钮对应显示的文字
*/
public MyCountTimer(long millisInFuture, long countDownInterval, TextView btn, String endStrRid) {
super(millisInFuture, countDownInterval);
this.btn = btn;
this.endStrRid = endStrRid;
}
/**
* 参数上面有注释
*/
public MyCountTimer(TextView btn, String endStrRid) {
super(TIME_COUNT, 1000);
this.btn = btn;
this.endStrRid = endStrRid;
}
@Override
public abstract void onFinish();
/**
* 计时过程显示
*/
@Override
public void onTick(long millisUntilFinished) {
// btn.setEnabled(false);
//每隔一秒修改一次UI
btn.setText(millisUntilFinished / 1000+"");
// 设置透明度渐变动画
final AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
//设置动画持续时间
alphaAnimation.setDuration(1000);
btn.startAnimation(alphaAnimation);
// 设置缩放渐变动画
final ScaleAnimation scaleAnimation =new ScaleAnimation(0.5f, 2f, 0.5f,2f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnimation.setDuration(1000);
btn.startAnimation(scaleAnimation);
}
}