Friday, May 25, 2012

Adobe AIR mobile app - how to get screen orientation?

In my recent project I had to get current screen orientation in my mobile app. How can you do this in Flex? I believe there are many ways to achieve that but here is my solution. First you need to write a function that checks Stage width and height:

 protected function currentOrientation():String
 {
  if (view.stage.width > view.stage.height)
   return "landscape";
  else
   return "portrait";
 }

OK that was easy but the real trick is to invoke that function when screen just changed its orientation. So another bit of code:
 stage.addEventListener(StageOrientationEvent.ORIENTATION_CHANGE, orientationChangeHandler);

 protected function orientationChangeHandler(event:StageOrientationEvent):void
 {
  trace("ORIENTATION: " + currentOrientation());
 }
Now when user rotates his device your app will immediately check the orientation of the screen.

No comments:

Post a Comment