Sunday, September 25, 2016

Sencha Touch Hide Alert Box on Android Back Button Press

Hello,

Recently in one my project our client gave use very strange requirement. We have used Sencha Touch to create application and used Cordova to create native app.

As we all know with Sencha Touch we use Ext.Msg.alert() to show user alert. This alert has OK button. When user tap on that alert goes away.

However in our case client asked us to hide this alert if its on and user presses virtual or physical hardware button of android phone. So after hearing this requirement first of I was confused and was not sure how to implement it. But after looking at docs and source code of Ext.Msg class solution was very easy so on this blog I am going to explain how to do this.

First of all we have to bind back button key event. Add following code to your app.js file.

if (Ext.os.is('Android')) {
            document.addEventListener("backbutton", Ext.bind(onBackKeyDown, this), false);
            function onBackKeyDown(e) {
            }
}

Now as we all know Ext.Msg is singleton class and the alerts and confirm boxes are nothing but a floating panels. So we can just simply check if it's hidden or not and hide it if required. Check the following code.


if (Ext.os.is('Android')) {
            document.addEventListener("backbutton", Ext.bind(onBackKeyDown, this), false);
            function onBackKeyDown(e) {
                     if(Ext.Msg.isHidden() !=  null){
                             if(Ext.Msg.isHidden() == false){
                                       Ext.Msg.hide();
                             }
                     }
                     else{
                             var comp = Ext.getCmp("ext-sheet-1");
                             if(comp){
                                 comp.hide();
                            }
                     }
                     e.preventDefault();
            }
}


As you can see in above code. First we are checking Ext.Msg.isHidden() !=  null, this is to check if there is no instance of alert is created yet, there is no meaning of hiding it.

Then we check if Ext.Msg.isHidden() == false then just hide it or else don't do anything. That's it. Hope this helps you.

No comments:

Post a Comment