Flex for Mobile – Device Form Factor Detection

Here’s a quick tip for detecting device form factor (tablet vs phone) within your Flex mobile applications. First, get the stage dimensions for the screen size in pixels, then divide that by the applicationDPI (screen pixel density).  This will give you the approximate size in inches of the device’s screen.   I say “approximate” because the pixel densities are rounded to 160, 240, or 320, depending on the device.    In my code, I make the assumption that if the landscape width is greater than or equal to 5 inches, then its a tablet.  I used view states, but you can also layout components manually.

Check out the code below:

[as3]<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:views="views.*"
resize="view1_resizeHandler(event)">

<fx:Script>
<![CDATA[

import mx.core.FlexGlobals;
import mx.events.ResizeEvent;

protected function view1_resizeHandler(event:ResizeEvent):void
{
var _width : Number = Math.max( stage.stageWidth, stage.stageHeight );
var _height : Number = Math.min( stage.stageWidth, stage.stageHeight );

_width = _width / FlexGlobals.topLevelApplication.applicationDPI;
_height = _height / FlexGlobals.topLevelApplication.applicationDPI;

//this will resolve to the physical size in inches…
//if greater than 5 inches, assume its a tablet
if ( _width >= 5 )
currentState = "tablet";
else
currentState = "phone";
}

]]>
</fx:Script>

<s:states>
<s:State name="tablet" />
<s:State name="phone" />
</s:states>

<views:PhoneView includeIn="phone"
width="100%" height="100%" />

<views:TabletView includeIn="tablet"
width="100%" height="100%" />

</s:View>[/as3]

This technique will enable you to build applications that tailor their interface to the types of devices where they are being consumed. If you’d like to read more, fellow Adobe Evangelist Michael Chaize also has a great example showing how to combine device form factor and orientation into Flex view states.

4 replies on “Flex for Mobile – Device Form Factor Detection”