美文网首页ionic开发Android开发
Ionic学习日记9:双击退出效果

Ionic学习日记9:双击退出效果

作者: SWKende | 来源:发表于2018-01-17 15:03 被阅读56次

前言

ionic开发出的app还是有些不方便的地方,比如不小心按返回键退出后,再打开还得等个一段时间,所以还是做一个这个效果出来方便调试等,这个功能也是市面上app必备的
本篇日记仅涉及到homepage

home.ts
  public backButtonPressed: boolean = false;

在constructor中添加,这些都会用上

    public navCtrl: NavController,
    public platform: Platform,
    public toastCtrl: ToastController,
    public app: App

同样在constructor内添加

  this.platform.ready().then(() => {
      //双击退出
      this.platform.registerBackButtonAction(() => {

        let activeVC = this.navCtrl.getActive();
        let page = activeVC.instance;
        if (page instanceof HomePage) {
          this.showExit();
        } else {
          this.app.goBack();
        }
      }, 999)
    });

做了一个判断,主要是区分当前的页面是不是HomePage,不是得话就是正常的goBack()效果,反之就触发showExit()方法,不做区分的话,从当前页面使用setRoot的方式跳转到其他的页面也会有双击退出的这个功能(如有特别的需要,也可以不用判断是不是HomePage)
PS:后面的999代表什么意思,暂时还不清楚

在class HomePage当中添加showExit()方法

showExit() {
    if (this.backButtonPressed) {
      this.platform.exitApp();
    } else {
      let toast = this.toastCtrl.create({
        message: '再按一次退出',
        duration: 2000,
        position: 'middle'
      })
      toast.present(toast);
      this.backButtonPressed = true;
      setTimeout(() => {
        this.backButtonPressed = false;
      }, 2000)
    }
  }

使用backButtonPressed判断是否可以退出,当它为true的时候再点击,才会进入第一个if的判断,退出app

相关文章

网友评论

    本文标题:Ionic学习日记9:双击退出效果

    本文链接:https://www.haomeiwen.com/subject/hqhuoxtx.html