Saturday 23 March 2013

Capture Orientation Change on Sencha Touch 2

Sencha Touch comes with lot of useful Features like containers, panels, layouts, grid, list and so on. In addition to that, Sencha Touch  also provides an ability to adjust your UI according to the size and orientation of user device.

Today, Let's see how we can add orientation change listener to Panel when user physically rotate his/her device.

Ext.define('MyApp.view.MyPanel', {
    extend: 'Ext.Panel',
    alias: 'widget.MyPanel',
    config: {
    height: '80%',
        html: 'Orientation Change Event',
        styleHtmlContent: true,
        width: '80%',
    },

    // Fires when the Panel is initialized
    initialize: function () {
        console.log('Panel initialize');
        // Add a Listener. Listen for [Viewport ~ Orientation] Change.
        Ext.Viewport.on('orientationchange', 'handleOrientationChange', this);
        this.callParent(arguments);

    },

    handleOrientationChange: function(viewport,orientation,width,height){
        // Execute the code that needs to fire on Orientation Change.
        Ext.Msg.alert("Orientation",orientation);

    }
});

Output:

When you run the above code in the Mobile Device and rotate it horizontal, alert Message with 'Landscape' will get displayed. By rotating it vertical, alert Message with 'Portrait' will get displayed

Event Listener can be added to any sencha touch component using on(). If you don't know, how to add event Listerner, Please click here. Orientation Change Event can be handled only through viewport using the below code

// Add a Listener. Listen for [Viewport ~ Orientation] Change.
Ext.Viewport.on('orientationchange', 'handleOrientationChange', this);

handleOrientationChange() method will be trigged, when viewport orientation changes. This method accept four parameters
  • viewport - Ext.Viewport
  • orientation - The new orientation
  • width - The width of the Viewport
  • height - The height of the Viewport
This feature is really useful, if you need to adjust the UI of any component based on the viewport orientation changes.

Hope, you enjoyed this Post.

5 comments:

  1. Thanks for the example. This is much easier to handle than going through the Ext.device api.

    ReplyDelete
  2. Hi,
    I am creating web app, i am facing an problem whenever i change the orientation app restarts how can i handle this? I googled but solution for android app only appears. Any suggestion?

    ReplyDelete
  3. No alert Message by Changing the Orientation!
    Exactly the same Code.
    Are there specific packages I need or do you maybe know what it could be that makes the app dont alert !

    ReplyDelete
  4. I tried it on my Acer Tablet, but it's still not working.
    'Panel initialisize' appears on my console, but nothing more.

    ReplyDelete