The browse for file functionality of the File class works a bit differently in Android as compared to the desktop. Within Android, the browseForOpen method will open up a specific native file selector that will allow you to open a file of type Audio, Image, or Video.
Let’s review the code below. The Button with the Browse label will call the button1_click Handler when clicked. Within this function, an instance of File is created with the variable name file. An event listener is added for Event.SELECT with the responding method of onFileSelect, and the browseForOpen method is called. The application can be seen in Figure 5-5. When browseForOpen is called, the Android file selector is launched. This can be seen in Figure 5-6. After selecting a file within the Android file selector, the event is fired and the onFileSelect method is called. The event.current Target is cast to a File object, and its nativePath, extension, and url properties are used to display the nativePath and the image in the example (shown in Figure 5-7):
<?xml version=”1.0″ encoding=”utf-8″?>
<s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009″
xmlns:s=”library://ns.adobe.com/flex/spark”>
<fx:Script>
<![CDATA[
protectedfunction button1_clickHandler(event:MouseEvent):void
{
var file:File = new File();
file.addEventListener(Event.SELECT, onFileSelect);
file.browseForOpen(“Open”);
}
privatefunction onFileSelect(event:Event):void {
var file:File = File(event.currentTarget);
filepath.text = file.nativePath;
if(file.extension == “jpg”){
image.source = file.url;
}
}
]]>
</fx:Script>
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>
<s:Button horizontalCenter=”0″ top=”10″ label=”Browse”
click=”button1_clickHandler(event)”/>
<s:Label id=”filepath” left=”10″ right=”10″ top=”100″/>
<s:Image id=”image” width=”230″ height=”350″ top=”150″ horizontalCenter=”0″/>
</s:Application>