简体   繁体   English

使用Ionic2 / angular2的设备(Android)后退按钮单击检测

[英]Device(Android) back button click detection using Ionic2/angular2

I am able to detect the device(Android) back button click event using the following code. 我可以使用以下代码检测设备(Android)后退按钮单击事件。 But after clicking the back button, it is going one level back and opening the confirmation dialog. 但是单击“后退”按钮后,它将返回上一级并打开确认对话框。

How do i avoid this behavior(going to the previous screen) using ionic2? 我如何使用ionic2避免这种现象(转到上一个屏幕)?

registerBackButtonListener() {              
        document.addEventListener('backbutton', () => {           
            let backBtnCnfirm = this.alertCtrl.create({
              message: 'Do you want to close the App?',
              buttons: [
              {
               text: 'Yes',
               handler: () => {
               this.platform.exitApp();
              }
            },
            {
             text: 'No',
             handler: () => {
            }
          }
        ]
       });
        backBtnCnfirm.present();
        }, false);
    }

The back button will call navCtrl.pop() , so going back to the previous page. 后退按钮将调用navCtrl.pop() ,因此返回上一页。 Ionic offers lifecycle events such as viewDidEnter, viewWillEnter, viewWillLeave etc. Ionic提供生命周期事件,例如viewDidEnter,viewWillEnter,viewWillLeave等。

When in your code you create this function: 在代码中创建此函数时:

ionViewWillLeave(){
   this.alertCtrl.create({
     message: 'Do you want to close the App?',
              buttons: [
              {
                text: 'Yes',
                handler: () => {
                  this.platform.exitApp();
               }
             },
             {
              text: 'No',
              role: 'cancel'
            }
           ]
   }).present();
}

Ionic will execute this before the navCtrl.pop() has been executed. Ionic将在执行navCtrl.pop()之前执行此操作。

Note: this will execute every time the page will leave (so when pushing or popping manually) but I think you're smart enough to find a workaround (boolean check fe) 注意:这将在每次页面离开时执行(因此,当手动推动或弹出页面时),但是我认为您足够聪明,可以找到解决方法(布尔检查功能)

(I don't know your requirements but I find it bad UX to show such a message when the backbutton is pressed, usually people would want to go a page back) (我不知道您的要求,但我发现按下后退按钮时显示这样的消息的用户体验不好,通常人们希望返回上一页)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM