ionic2 RC0 android物理键退出app

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

1. app.component.ts

@Component({
  template: ``
})
此处定义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中添加#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相同。


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







你可能感兴趣的:(ionic)