更新时间:2022-06-03 14:48:30浏览次数:283+次
以下介绍鸿蒙HarmonyOS ets语言怎么实现双击返回键退出的方法,采用HarmonyOS ARK UI技术实现,思路为:定义一个全局变量,判断点击时间与上一次点击时间差,若大于2秒则提示‘再按一次退出程序’字样,小于2秒退出应用。
源代码
import prompt from '@system.prompt';
import app from '@system.app'
@Entry
@Component
struct Index {
//todo 定义全局变量
@State exitTime: number= 0;
private onBackPress() {
this.ExitApp();
return true;
}
public ExitApp() {
//todo 判断点击时间与上一次点击时间差,若大于5秒则提示‘再按一次退出程序’字样
if ((new Date().getTime() - this.exitTime) > 5000) {
prompt.showToast({
message: '再按一次退出程序',
duration: 2000,
});
this.exitTime = new Date().getTime();
} else {
//todo 小于5秒退出应用
app.terminate();
}
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('双击返回app退出')
.fontSize(40)
.height(200)
.width("100%")
.textAlign(TextAlign.Center)
.fontWeight(FontWeight.Bold)
}
.width('100%')
.height('100%')
}
}
运行效果动画截图
上面的提示语也可根据自身的要求自定义。
相关资讯