ionic2 RC0 android物理键退出app

随着ionic2版本不断升级,退出app的方式也在不断变化,rc0尝试了多种方式,终于搞了一个可以使用的方法。

1. app.component.ts

@Component({
  template: `<ion-nav #rootNavController [root]="rootPage"></ion-nav>`
})
此处定义rootNavController,随后在MyApp中添加

export class MyApp {
  @ViewChild('rootNavController') navCtrl: NavController;
  rootPage = TabsPage;

  constructor(platform: Platform, public alertCtrl: AlertController) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();

      platform.registerBackButtonAction(() => {
        let activeVC = this.navCtrl.getActive();
        let activePage = activeVC.instance;

        if (!(activePage instanceof TabsPage)) {
          if (!this.navCtrl.canGoBack()) {
            return this.confirmExitApp();
          }
          return this.navCtrl.pop();
        }

        let tabs = activePage.tabRef.getSelected();
        let tabRoots = [activePage.tab1Root, activePage.tab2Root, activePage.tab3Root, activePage.tab4Root];
        let activeViewCtrl = tabs.getActive();
        if (activeViewCtrl.name == tabRoots[tabs.index].name) {
          this.confirmExitApp();
        } else {
          activeViewCtrl.getNav().pop();
        }
      });
    });
  }

  confirmExitApp() {
    let alert = this.alertCtrl.create({
      title: "exit prompt",
      message: "Confirm exit app?",
      buttons: [
        {
          text: "cancel"
        },
        {
          text: "ok",
          handler: () => {
            navigator['app'].exitApp();
          }
        }
      ]
    });
    alert.present();
  }
}

2. tabs.html

<ion-tabs tabsPlacement="bottom" #myTabs>
</ion-tabs>
此处在ion-tabs中添加#myTabs

3. tabs.ts

同样在此处定义ViewChild

export class TabsPage {

  @ViewChild('myTabs') tabRef: Tabs;

  // this tells the tabs component which Pages
  // should be each tab's root Page
  tab1Root: any = Tab1Page;
  tab2Root: any = Tab2Page;
  tab3Root: any = Tab3Page;
  tab4Root: any = Tab4Page;

  constructor() {

  }
}


主要说明一下registerBackButtonAction,首先得到rootPage,代码中为activePage,如果不是TabsPage则直接处理。

如果是TabsPage,通过tabRef得到当前选中哪个,然后判断当前page的name是否与tab1Root、tab2Root等几个rootPage

的name相同。


如果有更简单方法望告知,谢谢!







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值