android硬件中的返回按钮如何利用ionic2进行处理
发布时间:2020-12-02 15:29:43
来源:亿速云
阅读:74
作者:Leah
本篇文章给大家分享的是有关android硬件中的返回按钮如何利用ionic2进行处理,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
问题
注册安卓硬件返回按钮事件是必须的,因为用户不小心点击了返回按钮就退出app体验很不好,所以有几种方法:
1.实现按返回键最小化应用(最小化应用需要装cordova-plugin-appminimize插件,使用window['AppMinimize'].minimize();)。
2.要么请求用户确认(添加一个Confirmation Alerts)。
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'
})
export class MyApp {
rootPage = TabsPage;
backButtonPressed: boolean = false; //用于判断返回键是否触发
@ViewChild('myNav') nav: Nav;
constructor(public ionicApp: IonicApp, public platform: Platform, public toastCtrl: 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()
let activePortal = this.ionicApp._modalPortal.getActive();
if (activePortal) {
activePortal.dismiss().catch(() => {});
activePortal.onDidDismiss(() => {});
return;
}
let activeVC = this.nav.getActive();
let tabs = activeVC.instance.tabs;
let activeNav = tabs.getSelected();
return activeNav.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'
})
export class TabsPage {
@ViewChild('mainTabs') tabs:Tabs;//加这句以及引用两个模块
tab1Root: any = HomePage;
tab2Root: any = AboutPage;
tab3Root: any = ContactPage;
constructor() {
}
}
以上就是android硬件中的返回按钮如何利用ionic2进行处理,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。