![](https://s5-media.51cto.com/ost/pc/static/noavatar.gif)
回复
本篇将带你实现一个自定义天气预报组件。用户可以通过选择不同城市来获取相应的天气信息,页面会显示当前城市的天气图标、温度及天气描述。这一功能适合用于动态展示天气信息的小型应用。
自定义天气预报组件通过静态数据模拟天气服务,用户可以选择城市,并实时显示该城市的天气信息,包括天气图标、温度及文字描述。
@Entry
和 @Component
装饰器Column
和 Row
布局组件Text
组件用于显示天气信息Button
组件用于城市选择@State
修饰符用于状态管理Image
组件用于展示天气图标WeatherForecastApp
WeatherForecastPage
WeatherForecastPage.ets
、Index.ets
// 文件名:WeatherForecastPage.ets
@Component
export struct WeatherForecastPage {
@State selectedCity: string = '北京'; // 默认城市
@State weatherIcon: string = 'app.media.sunny';
@State temperature: string = '25°C';
@State description: string = '晴天';
// 更新天气信息
updateWeather() {
if (this.selectedCity === '北京') {
this.weatherIcon = 'app.media.sunny';
this.temperature = '25°C';
this.description = '晴天';
} else if (this.selectedCity === '上海') {
this.weatherIcon = 'app.media.rainy';
this.temperature = '18°C';
this.description = '小雨';
} else if (this.selectedCity === '广州') {
this.weatherIcon = 'app.media.cloudy';
this.temperature = '28°C';
this.description = '多云';
}
}
build() {
Column({ space: 20 }) {
Text('请选择城市:')
.fontSize(20)
.alignSelf(ItemAlign.Start);
// 城市按钮
Button('北京')
.onClick(() => {
this.selectedCity = '北京'; // 设置选择的城市
this.updateWeather(); // 更新天气信息
});
Button('上海')
.onClick(() => {
this.selectedCity = '上海';
this.updateWeather();
});
Button('广州')
.onClick(() => {
this.selectedCity = '广州';
this.updateWeather();
});
// 展示天气信息
Column({ space: 10 }) {
Image($r(this.weatherIcon)) // 动态显示天气图标
.width(100)
.height(100)
.alignSelf(ItemAlign.Center);
Text(`${this.selectedCity} - ${this.temperature}`)
.fontSize(24)
.fontWeight(FontWeight.Bold)
.alignSelf(ItemAlign.Center);
Text(this.description)
.fontSize(18)
.alignSelf(ItemAlign.Center);
}
}
.padding(20)
.width('100%')
.height('100%');
}
}
// 文件名:Index.ets
import { WeatherForecastPage } from './WeatherForecastPage';
@Entry
@Component
struct Index {
build() {
Column() {
WeatherForecastPage() // 调用天气预报页面
}
.padding(20)
}
}
效果示例:用户可以通过点击城市按钮(如北京、上海、广州)实时查看该城市的天气图标、温度及描述。
城市选择功能
Button
组件创建多个城市选择按钮,用户点击按钮后会更新显示该城市的天气信息。状态管理
@State
修饰符管理当前选择的城市、天气图标、温度和天气描述,实现动态更新。天气信息展示
Image
组件动态显示天气图标,Text
组件展示城市、温度及天气描述。支持动态数据源
添加更多天气数据
UI美化
通过自定义天气预报组件的实现,用户可以体验到基于静态数据的城市选择与天气展示功能。该应用适合用于天气展示及实时状态更新的场景。
在下一篇「UI互动应用篇24 - 虚拟音乐控制台」中,我们将探讨如何实现一个虚拟音乐控制台,支持播放、暂停、切换歌曲等功能,为用户提供完整的音乐交互体验。
作者:SoraLuna
链接:https://www.nutpi.net/thread?topicId=501
來源:坚果派
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。