天气预报程序

天气预报程序

暂未完成定位功能版本

import getweatherUtil from "../pages/getWeatherUtil";
import { WeatherModel } from "../pages/WeatherModel";
import { cityView } from './cityView';
import { router } from '@kit.ArkUI';
​
@Entry
@Component
struct Index {
  // 城市代码、名字、信息
  @State cityCodeList: number[] = [110000, 120000];
  @State cityNameList: string[] = [];
  @State cityWeatherList: Array<WeatherModel> = [];
  @State cityIndex: number = 0;
  @State bgpictures: string[] = [];  // 改为数组存储每个城市的背景图片路径
​
  // 根据天气设置背景图片
  setBgPicture(weather: string, index: number) {  // 添加索引参数
    if (weather === '晴') {
      this.bgpictures[index] = 'app.media.bgqingtian';
    } else if (weather === '阴') {
      this.bgpictures[index] = 'app.media.bgyintian';
    } else if (weather === '多云') {
      this.bgpictures[index] = 'app.media.bgduoyun';
    } else if (weather.includes('雨')) {
      this.bgpictures[index] = 'app.media.bgrain';
    }
  }
​
  tabController: TabsController = new TabsController();
​
  @Builder tabBuild(index: number) {
    Circle({ width: 10, height: 10 })
      .fill(this.cityIndex === index? Color.White: Color.Gray)
      .opacity(0.4)
  }
​
  onPageShow() {
    interface Params {
      codes: number[];
      names: string[];
    }
​
    let params = router.getParams() as Params;
    if (params!== null) {
      this.cityCodeList = params.codes;
      this.cityNameList = params.names;
​
      this.cityWeatherList = [];
      this.cityNameList = [];
      this.initDate();
    }
  }
​
  // 获取数据
  aboutToAppear() {
    this.initDate();
  }
​
  // 初始化方法
  async initDate() {
    let result: Array<WeatherModel> = await getweatherUtil.getWeathers(this.cityCodeList);
​
    for (let i = 0; i < result.length; i++) {
      let ACityWeather = new WeatherModel();
      ACityWeather = result[i];
      this.cityWeatherList.push(ACityWeather);
      let cityName = result[i].forecasts[0].city;
      this.cityNameList.push(cityName);
      // 根据天气设置背景图片
      this.setBgPicture(result[i].forecasts[0].casts[0].dayweather, i);  // 传递索引
    }
  }
​
  // 数据展示
  build() {
    Column() {
      Row() {
        Image($r('app.media.add'))
          .width(30)
          .height(30)
          .opacity(1)
          .margin({ bottom: 15 })
          .onClick(() => {
            router.pushUrl({
              url: "pages/AddCity",
              params: {
                codes: this.cityCodeList,
                names: this.cityNameList
              }
            })
          })
        Text(this.cityNameList[this.cityIndex])
          .fontSize(35).fontColor(Color.Black).fontWeight(FontWeight.Bold)
        Image($r('app.media.delete'))
          .opacity(1)
          .width(35)
          .height(35)
          .margin({ bottom: 15 })
          .onClick(() => {
​
            AlertDialog.show({
              title: "删除",
              message: `你确定要删除${this.cityNameList[this.cityIndex]}吗?`,
              confirm: {
                value: "确定",
                action: () => {
                  this.cityNameList = this.cityNameList.filter(item => item!== this.cityNameList[this.cityIndex]);
                  this.cityCodeList = this.cityCodeList.filter(item => item!== this.cityCodeList[this.cityIndex]);
                  this.cityWeatherList = this.cityWeatherList.filter(item => item!== this.cityWeatherList[this.cityIndex]);
                }
              }
            })
          })
      }.backgroundColor(Color.White).opacity(0.7)
      .width('100%').height('10%').justifyContent(FlexAlign.SpaceBetween)
      .margin({ top: '0.00vp', right: '30.00vp', bottom: '0.00vp', left: '30.00vp' })
​
      Tabs({ barPosition: BarPosition.Start, controller: this.tabController }) {
        ForEach(this.cityWeatherList, (cityWeather: WeatherModel, index: number) => {  // 添加索引
          TabContent() {
            cityView({ casts: cityWeather.forecasts[0].casts })
          }.tabBar(this.tabBuild(index))  // 传递索引
        })
      }
      .barWidth(40)
      .barHeight(40)
      .onChange((index: number) => {
        this.cityIndex = index;
      })
    }
    .backgroundImage($r(this.bgpictures[this.cityIndex]))  // 根据当前城市索引获取背景图片
    .backgroundImageSize({ width: '100%', height: '100%' })
    .width('100%').height('100%')
  }
}
import {casts}from '../pages/casts'
​
@Component
export struct cityView{
  @Builder weartherImage(weather:string){
      if (weather==='晴') {
        Image($r('app.media.qingtian')).width(30)
      }
      if (weather==='阴') {
        Image($r('app.media.yintian')).width(30)
      }
      if (weather==='多云') {
        Image($r('app.media.duoyun')).width(30)
      }
      if (weather.includes('雨')) {
        Image($r('app.media.rain')).width(30)
      }
    }
​
​
  casts:Array<casts>=[]
  build() {
    Scroll() {
      Column() {
        ForEach(this.casts, (cast: casts) => {
          if (this.casts[0] === cast) {
            Row() {
              if (cast.dayweather === '晴') {
                Image($r('app.media.qingtian')).width(160)
              }
              if (cast.dayweather === '阴') {
                Image($r('app.media.yintian')).width(160)
              }
              if (cast.dayweather === '多云') {
                Image($r('app.media.duoyun')).width(160)
              }
              if (cast.dayweather.includes('雨')) {
                Image($r('app.media.rain')).width(160)
              }
            }.height('20%')
​
            Column() {
              Row() {
                Text(cast.date).fontSize(30).fontColor(Color.Black)
              }.height(40)
              Row() {
                Text(cast.dayweather).fontSize(35).fontColor(Color.Black)
                Text(' ' + cast.daytemp + "° ~" + cast.nighttemp + "°")
                  .fontSize(35)
                  .fontColor(Color.Black )
              }.height(40)
              .margin({ top: '10.00vp', right: '0.00vp', bottom: '0.00vp', left: '0.00vp' })
​
              Row() {
                Text(cast.daywind + "风").fontSize(35).fontColor(Color.Black)
                Text(cast.daypower + "级").fontSize(35).fontColor(Color.Black)
              }.height(40)
              .margin({ top: '0.00vp', right: '0.00vp', bottom: '10.00vp', left: '0.00vp' })
              Blank(10)
              Row(){
                Column() {
                  Text(`夜间${cast.nightweather}`).fontSize(25).fontColor(Color.Black).fontWeight(FontWeight.Normal)
                  Text(cast.daytemp + "° ~" + cast.nighttemp + "°")
                    .fontSize(25)
                    .fontColor(Color.Black)
                    .fontWeight(FontWeight.Normal)
                }.borderRadius(10).height(100).width(150).backgroundColor(Color.White).opacity(0.8).justifyContent(FlexAlign.Center)
                Column(){
                Text(`夜间${cast.nightwind}风`).fontSize(25).fontColor(Color.Black).fontWeight(FontWeight.Normal)
                  Text(cast.nightpower + "级")
                  .fontSize(25)
                  .fontColor(Color.Black)
                  .fontWeight(FontWeight.Normal)
              } .borderRadius(10).height(100).width(150).backgroundColor(Color.White).opacity(0.8).justifyContent(FlexAlign.Center)
              }.width('96%').justifyContent(FlexAlign.SpaceAround)
              .margin({ top: '10.00vp', right: '0.00vp', bottom: '0.00vp', left: '0.00vp' })
            }.margin({ top: 10 })
          }
        })
        Column() {
          Text('近期天气查询')
            .fontSize(26)
            .margin({
              top: '30.00vp',
              right: '0.00px',
              bottom: '20.00px',
              left: '0.00px'
            })
          Row() {
            ForEach(this.casts, (cast: casts) => {
              Column() {
                Text(cast.date.substring(5))
                this.weartherImage(cast.dayweather)
                Text(cast.daytemp.toString())
                Line()
                  .width(20)
                  .height(65)
                  .startPoint([10, 5])
                  .endPoint([10, 55])
                  .stroke(Color.Gray)
                  .strokeWidth(2)
                  .strokeDashArray([7, 4])
                Text(cast.nighttemp.toString())
                this.weartherImage(cast.nightweather)
              }.width('20%').height('90%')
            })
          }.borderRadius(5)
          .width('80%')
          .height('60%')
          .backgroundColor(Color.White)
          .opacity(0.8)
          .justifyContent(FlexAlign.SpaceAround)
          .margin({
            top: '10.00vp',
            right: '0.00vp',
            bottom: '0.00vp',
            left: '0.00vp'
          })
        }.width('100%').height('55%')
​
​
      }.width('100%')
    }
  }
}
import {WeatherModel}from"../pages/WeatherModel"
import { http } from '@kit.NetworkKit'
​
class getWeatherUtil{
​
  getWeather(cityCode:number){
    return new Promise<WeatherModel>((resolve,reject)=>{
      let request=http.createHttp()
      let url=`https://restapi.amap.com/v3/weather/weatherInfo?city=${cityCode}&key=73f58ea81f2a425f22cc9a2655338f70&extensions=all`
​
      let result=request.request(url)
      result.then((res)=>{
        if(res.responseCode===200){
          console.log(res.result.toString());
          resolve(JSON.parse(res.result.toString()))
        }
      }).catch((err:string)=>{
        console.log(err)
      })
    })
  }
  //直接发送多个URL结果一并返回
  async getWeathers(cityCode:Array<number>){
  let promises:Array<Promise<WeatherModel>>=[]
  let weatherModels:Array<WeatherModel>=[]
    for (let i = 0; i < cityCode.length; i++) {
      promises.push(this.getWeather(cityCode[i]))
    }
​
   await Promise.all(promises).then(result=>{
     for (const element of result) {
       console.log(element.forecasts[0].city)
     }
     weatherModels=result
   })
    return weatherModels
  }
}
​
let getweatherUtil=new getWeatherUtil()
export default getweatherUtil as getWeatherUtil
import { router } from '@kit.ArkUI';
​
@Entry
@Component
struct AddCity {
​
  @State AllCityCodeList:Array<number>=[110000,120000,130000,140000,210000,220000,310000]
  @State AllCityNameList:Array<string>=['北京市','天津市','河北省','山西省','辽宁省','吉林省','上海市']
  @State cityCodeList:number[]=[]
  @State cityNameList:string[]=[]
  onPageShow() {
    interface Params {
      codes: number[];
      names: string[];
    }
​
    let params = router.getParams() as Params;
    this.cityCodeList = params.codes;
    this.cityNameList = params.names;
  }
​
​
  build() {
    Column(){
      Row(){
        Text('添加城市列表').fontSize(35).fontColor(Color.Black)
        Blank()
        Button('完成').fontSize(26).fontColor(Color.Black).backgroundColor('#ff9dcdf6')
          .onClick(()=>{
            router.back({
              url:"pages/Index",
              params:{
                codes:this.cityCodeList,
                names:this.cityNameList
              }
            })
          })
      }.height('10%').width('95%')
      Column(){
        Row() {
          Text('定位查找').fontSize(32).fontColor(Color.Gray)
        }.width('100%')
        .justifyContent(FlexAlign.Start)
        .margin({ top: '0.00vp', right: '0.00vp', bottom: '0.00vp', left: '25.00vp' })
        List(){
          ForEach(this.AllCityNameList,(name:string)=>{
            ListItem(){
              if(this.cityNameList.includes(name)){
                Column(){
                  Row(){
                    Text(name).fontSize(28).fontColor(Color.Black).width('60%').margin({top:20,left:30})
                    Blank()
                    Text('已添加').fontSize(20).fontColor(Color.Black).margin({top:20}).opacity(0.8)
                  }.width('100%')
                  Blank()
                  Divider().strokeWidth(5)
                }.height(90).width('100%').margin({top:20}).backgroundColor('#44b5e0f8')
              }else {
                Column(){
                  Row(){
                    Text(name).fontSize(28).fontColor(Color.Black).width('60%').margin({top:20,left:30})
                    Blank()
                    Button('添加').backgroundColor('#ff9dcdf6').fontSize(18).margin({right:5})
                      .onClick(()=>{
                        let index=this.AllCityNameList.findIndex(obj=>obj===name)
                        let citycode:number=this.AllCityCodeList[index]
                        this.cityCodeList.push(citycode)
                        this.cityNameList.push(name)
                      })
                  }.width('100%')
                  Blank()
                  Divider().strokeWidth(5)
                }.height(90).width('100%').margin({top:20})
              }
            }
          })
        }
      }.width('100%').height('90%')
    }.width('100%').height('100%').backgroundColor("#fffeffff")
  }
}
export class casts {
  date: string;
  dayweather: string;
  nightweather: string;
  daytemp: number;
  nighttemp: number;
  daywind: string;
  nightwind: string;
  daypower: string;
  nightpower: string;
  daytemp_float: number;
  nighttemp_float: number;
​
  constructor() {
    this.date = '';
    this.dayweather = ''; // 为 dayweather 赋值
    this.nightweather = '';
    this.daytemp = 0;
    this.nighttemp = 0;
    this.daywind = '';
    this.nightwind = '';
    this.daypower = '';
    this.nightpower = '';
    this.daytemp_float = 0;
    this.nighttemp_float = 0;
  }
}
import {casts}from "../pages/casts"
​
export class forecasts {
  city: string;
  adcode: number;
  casts: Array<casts>;
​
  constructor() {
    this.city = '';  // 为 city 赋值
    this.adcode = 0;
    this.casts = [];
  }
}
  • 37
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Studio是一款功能强大的集成开发环境,可以用于开发各种Android应用程序,包括天气预报程序。 对于天气预报程序的开发,首先要获取天气数据。可以通过使用第三方的天气API来获取实时的天气数据。开发者可以选择合适的API,注册并获取相应的API密钥。 在Android Studio中,可以创建一个新的项目,并添加必要的权限和依赖库。然后创建一个主界面,在界面上展示天气信息。主界面上可以添加一个输入框,用于用户输入城市名称,然后通过点击按钮来获取相应城市的天气数据。 在点击按钮之后,程序会利用API密钥和用户输入的城市名称,发送HTTP请求到天气API接口,获取天气数据的JSON数据。通过解析JSON数据,可以得到需要的天气信息,例如温度、湿度、风力等等。 然后可以将获取到的天气数据展示到主界面上,可以使用TextView来显示温度、湿度等信息,并使用图片来展示天气状况(如晴天、多云等)。同时,还可以添加其他功能,例如未来几天的天气预报、生活指数等等。 为了提供更好的用户体验,可以对界面进行美化和优化。例如使用适当的颜色和布局,确保界面简洁明了。还可以加入下拉刷新功能,使用户可以手动刷新天气数据。还可以为天气预报程序添加通知功能,当有特殊天气情况时,发送通知给用户。 总而言之,使用Android Studio可以方便地开发天气预报程序。通过获取天气API的数据,解析JSON数据,以及合理设计和展示界面,可以实现一个功能完善的天气预报程序,并为用户提供准确、及时的天气信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值