第12章:构建一个天气应用
UI界面开发
1. 界面结构设计
1.1 主界面布局
- 顶部区域:城市选择栏 + 天气状态图标
- 中部区域:当前温度展示 + 天气描述
- 底部区域:未来几天天气预报卡片列表
- 扩展区域(滑动展开):湿度、风速等详细信息
1.2 组件层级规划
Column() {
// 顶部城市栏
WeatherHeader()
// 主天气信息
CurrentWeatherDisplay()
// 预报卡片列表
ForecastList()
// 扩展信息面板
WeatherDetailsPanel()
}
2. 核心组件实现
2.1 天气卡片组件
@Component
struct WeatherCard {
@Prop day: string
@Prop icon: Resource
@Prop tempRange: string
build() {
Column() {
Text(this.day)
.fontSize(16)
Image(this.icon)
.width(40)
.height(40)
Text(this.tempRange)
.fontColor('#666')
}
.padding(10)
.borderRadius(8)
.backgroundColor('#FFF')
}
}
2.2 动态天气图标
function getWeatherIcon(condition: string): Resource {
switch(condition) {
case 'sunny': return $r('app.media.ic_sunny')
case 'rainy': return $r('app.media.ic_rain')
// ...其他天气状态
}
}
3. 样式与主题
3.1 颜色方案
/* 日间模式 */
:root {
--primary-color: #4285f4;
--bg-color: #f5f5f5;
--card-color: #ffffff;
}
/* 夜间模式 */
.dark {
--primary-color: #8ab4f8;
--bg-color: #121212;
--card-color: #1e1e1e;
}
3.2 响应式布局
@Extend(Text) function responsiveText() {
.fontSize(this.width > 600 ? 18 : 14)
.margin({ top: this.height > 800 ? 10 : 5 })
}
4. 交互设计
4.1 城市选择器
@State cityList: Array<string> = ['北京', '上海', '广州']
@State selectedCity: string = '北京'
Picker({ options: this.cityList })
.onChange((value: string) => {
this.selectedCity = value
this.fetchWeatherData()
})
4.2 下拉刷新
List() {
// 列表内容...
}
.onRefresh(() => {
this.refreshing = true
this.fetchWeatherData()
})
.refreshable(true)
5. 调试技巧
- 布局边界检查:开启开发者选项中的布局边界显示
- 动态样式调试:使用实时预览工具调整间距和颜色
- 多设备适配:利用预览器的多种分辨率模式测试
- 性能分析:通过ArkTS Profiler检测渲染性能
6. 完整示例代码结构
weather-app/
├── components/
│ ├── WeatherCard.ets
│ ├── CityPicker.ets
│ └── ForecastList.ets
├── pages/
│ └── HomePage.ets
└── models/
└── WeatherData.ets
最佳实践提示:
- 使用Flex布局确保不同屏幕尺寸的适配性
- 对高频更新的组件使用@ObjectLink优化渲染
- 复杂动画建议使用Lottie实现
- 图标资源建议使用SVG格式保证清晰度
