ionic2如何处理android硬件返回按钮
问题
注册安卓硬件返回按钮事件是必须的,因为用户不小心点击了返回按钮就退出app体验很不好,所以有几种方法:
1.实现按返回键最小化应用(最小化应用需要装cordova-plugin-appminimize插件,使用window['AppMinimize'].minimize();)。
2.要么请求用户确认(添加一个ConfirmationAlerts)。
3.按一下提示,按两下退出(加一个方法用toast提醒)。
这里用第三种展示。
解决
在app.html中,添加#myNav,在app.component.ts文件通过@ViewChild('myNav')获取:
在app.component.ts中:
import{Component,ViewChild}from'@angular/core';
import{Platform,ToastController,Nav,IonicApp}from'ionic-angular';
import{StatusBar,Splashscreen}from'ionic-native';
import{TabsPage}from'../pages/tabs/tabs';
@Component({
templateUrl:'app.html'
})
exportclassMyApp{
rootPage=TabsPage;
backButtonPressed:boolean=false;//用于判断返回键是否触发
@ViewChild('myNav')nav:Nav;
constructor(publicionicApp:IonicApp,publicplatform:Platform,publictoastCtrl:ToastController){
platform.ready().then(()=>{
StatusBar.styleDefault();
Splashscreen.hide();
this.registerBackButtonAction();//注册返回按键事件
});
}
registerBackButtonAction(){
this.platform.registerBackButtonAction(()=>{
//如果想点击返回按钮隐藏toast或loading或Overlay就把下面加上
//this.ionicApp._toastPortal.getActive()||this.ionicApp._loadingPortal.getActive()||this.ionicApp._overlayPortal.getActive()
letactivePortal=this.ionicApp._modalPortal.getActive();
if(activePortal){
activePortal.dismiss().catch(()=>{});
activePortal.onDidDismiss(()=>{});
return;
}
letactiveVC=this.nav.getActive();
lettabs=activeVC.instance.tabs;
letactiveNav=tabs.getSelected();
returnactiveNav.canGoBack()?activeNav.pop():this.showExit();//另外两种方法在这里将this.showExit()改为其他两种的方法的逻辑就好。
},1);
}
//双击退出提示框
showExit(){
if(this.backButtonPressed){//当触发标志为true时,即2秒内双击返回按键则退出APP
this.platform.exitApp();
}else{
this.toastCtrl.create({
message:'再按一次退出应用',
duration:2000,
position:'top'
}).present();
this.backButtonPressed=true;
setTimeout(()=>this.backButtonPressed=false,2000);//2秒内没有再次点击返回则将触发标志标记为false
}
}
}
在tabs.html中,添加#mainTabs,在tabs.ts文件通过@ViewChild('mainTabs')tabs:Tabs;获取:
在tabs.ts中:
import{Component,ViewChild}from'@angular/core';
import{HomePage}from'../home/home';
import{AboutPage}from'../about/about';
import{ContactPage}from'../contact/contact';
import{Tabs}from"ionic-angular";
@Component({
templateUrl:'tabs.html'
})
exportclassTabsPage{
@ViewChild('mainTabs')tabs:Tabs;//加这句以及引用两个模块
tab1Root:any=HomePage;
tab2Root:any=AboutPage;
tab3Root:any=ContactPage;
constructor(){
}
}
完成。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。