【HarmonyOS】【ARK UI】HarmonyOS ets语言怎么实现双击返回键退出

参考资料

【Harmony OS】【ARK UI】Date 基本操作

自定义组件生命周期回调函数

弹窗

代码运行

思路:

定义一个全局变量,判断点击时间与上一次点击时间差,若大于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%')
  }
}

【HarmonyOS】【ARK UI】HarmonyOS ets语言怎么实现双击返回键退出

运行效果

欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh

Original: https://www.cnblogs.com/developer-huawei/p/16534245.html
Author: 华为开发者论坛
Title: 【HarmonyOS】【ARK UI】HarmonyOS ets语言怎么实现双击返回键退出

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/551617/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球