Flex实现简易天气预报客户端

新手接触Flex开发,希望通过实践来加深书面知识的理解。

本文以期实现Flex版天气预报客户端,将该任务粗略的分为两部分:一是从网络获取天气预报数据;二是展示天气预报信息。

如何获取天气预报数据?网络上有不少天气类相关的网站提供了RSS订阅服务,于是可以通过RSS获取天气预报信息,本文从http://weather.raychou.com/?/list/上获取天气预报数据。

对于Flex,可以利用HTTPService类来完成与服务器的通信,调用 HTTPService 对象的 send() 方法,将发出对指定 URL 的 HTTP 请求,并且返回 HTTP 响应。代码如下:

protected function btnGetSinaInfo_clickHandler(event:MouseEvent):void
{
	// TODO Auto-generated method stub
	var hsWeatherPrediction:HTTPService = new HTTPService();
	hsWeatherPrediction.url = "http://weather.raychou.com/?/detail/57494/rss";
	hsWeatherPrediction.useProxy = false;
	hsWeatherPrediction.showBusyCursor = true;
	hsWeatherPrediction.addEventListener(ResultEvent.RESULT, loadResult);
	hsWeatherPrediction.send();
}

UI的设计与实现是个精细活,俺水平也有限也耗不起那时间,就来个粗糙的,用Flex的DataGrid组件将HTTP请求结果展示出来。最终效果如下:

全部源代码如下:

<?xml version="1.0"?>
<!-- Simple example to demonstrate the VBox layout container. -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
	<mx:Script>
		<![CDATA[
			import mx.rpc.events.ResultEvent;
			import mx.rpc.http.HTTPService;
			
			protected function btnGetWeatherInfo_clickHandler(event:MouseEvent):void
			{
				// TODO Auto-generated method stub
				var hsWeatherPrediction:HTTPService = new HTTPService();
				hsWeatherPrediction.url = "http://weather.raychou.com/?/detail/57494/rss";
				hsWeatherPrediction.useProxy = false;
				hsWeatherPrediction.showBusyCursor = true;
				hsWeatherPrediction.addEventListener(ResultEvent.RESULT, loadResult);
				hsWeatherPrediction.send();
			}
			
			private function loadResult(event:ResultEvent):void{
				weatherContent.dataProvider = event.result.rss.channel.item;
			}
		]]>
	</mx:Script>
	
	<mx:Panel title="武汉地区一周天气预报_简易版" height="60%" width="75%"
			  paddingTop="10" paddingLeft="30" paddingRight="30" paddingBottom="10">
		<mx:HBox>
			<mx:Button id="btnGetWeatherInfo" label="获取天气预报" click="btnGetWeatherInfo_clickHandler(event)"/>
			<mx:LinkButton label="更多天气信息" click="navigateToURL(new URLRequest('http://weather.raychou.com/?/list/'))"/>
		</mx:HBox>
		<mx:DataGrid id="weatherContent" width="100%" height="80%">
			<mx:columns>
				<mx:DataGridColumn  width="40" headerText="日期" dataField="title"/>
				<mx:DataGridColumn  width="60" headerText="天气" dataField="description" />
			</mx:columns>
		</mx:DataGrid>
		<mx:TextArea id="resultText" width="100%" height="15%" htmlText="{weatherContent.selectedItem.title + ': ' + weatherContent.selectedItem.description}"/>
	</mx:Panel>
</mx:Application>
原文地址:https://www.cnblogs.com/hans_gis/p/2600024.html