HarmonyOS 鸿蒙Next 实现从一个时间开始正计时的效果?例如从00:20开始正计时
HarmonyOS 鸿蒙Next 实现从一个时间开始正计时的效果?例如从00:20开始正计时
实现从一个时间开始正计时的效果?例如从00:20开始正计时
2 回复
TextTimer暂时不支持指定数字正计数,可以自定义一个计时器实现,参考demo:
[@Entry](/user/Entry)
[@Component](/user/Component)
struct Index{
textTimerController:TextTimerController=new TextTimerController()
[@State](/user/State) format:string='mm:ss.SS'
[@State](/user/State) delay:number=30
[@State](/user/State) countDownTimeText:string=''
[@State](/user/State) hourTime:number=0
[@State](/user/State) minuteTime:number=0
[@State](/user/State) secondTime:number=0
[@State](/user/State) order:boolean=true
[@State](/user/State) countDownTime:number=20000
[@State](/user/State) timer:number=0
timeToString(value:number){//毫秒时间转换
let secondTime=value/1000, //秒
minuteTime=0,//分
hourTime=0;//时
if(secondTime>60){//如果秒数大于60,将秒数转换成整数
minuteTime=secondTime/60; //获取分钟,除以60取整数
secondTime=secondTime%60; //获取秒数,秒数取余取整
if(minuteTime>60){
hourTime=minuteTime/60;
minuteTime=minuteTime%60
}
}
let result="";
result=""+this.sizeFormat(secondTime)+""+result
if(minuteTime>=0){
result=""+this.sizeFormat(minuteTime)+":"+result
}
if(this.hourTime>=0){
result=""+this.sizeFormat(hourTime)+":"+result
}
//保存时间数据
this.countDownTimeText=result
this.hourTime=hourTime
this.minuteTime=minuteTime
this.secondTime=secondTime
this.secondTime=secondTime
return result;
}
sizeFormat(val:number){
return val>=10?''+val:'0'+val
}
startTiming(){
if(!this.order){
this.timer=setInterval(()=>{
this.timeToString(this.countDownTime);
this.countDownTime=this.countDownTime-this.delay;
if(this.countDownTime<=0){
this.countDownTimeText='00:00:00';
clearTimeout(this.timer);
}
},this.delay)
}else{
this.order=true;
this.timer=setInterval(()=>{
this.timeToString(this.countDownTime);
this.countDownTime=this.countDownTime+this.delay
},this.delay)
}
}
build() {
Column(){
Text(("计时:")+(this.countDownTimeText)).fontColor(Color.Black)
Row(){
Button("start").onClick(()=>{
clearInterval(this.timer)
this.startTiming()
})
Button("pause").onClick(()=>{
clearInterval(this.timer)
})
Button("reset").onClick(()=>{
this.countDownTime=20000
this.order=true
this.timeToString(this.countDownTime)
clearInterval(this.timer)
})
}
}
}
}
更多关于HarmonyOS 鸿蒙Next 实现从一个时间开始正计时的效果?例如从00:20开始正计时的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html