天天看點

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相同。

如果有更簡單方法望告知,謝謝!