当前位置: 首页 > article >正文

鸿蒙中选择地区

1.首页ui


import { CustomDialogExampleSelectRegion } from './selectRegion/SelectRegionDialog';


@Entry
@Component
struct Index {
  @State selectedRegion: string = '选择地区'
  // 地区
  dialogControllerSelectRegion: CustomDialogController | null = new CustomDialogController({
    builder: CustomDialogExampleSelectRegion({
      selectedRegion: this.selectedRegion
    }),
    autoCancel: true,
    alignment: DialogAlignment.Center,
    onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
      console.info("reason=" + JSON.stringify(dismissDialogAction.reason))
      console.log("dialog onWillDismiss")
      if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
        dismissDialogAction.dismiss()
      }
      if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
        dismissDialogAction.dismiss()
      }
    },
    width: 300,
    height: 340,
    offset: { dx: 0, dy: -25 }
  })

  build() {
    Column() {
      Button(this.selectedRegion).onClick(() => {
        this.dialogControllerSelectRegion?.open()
      })
    }
    .width('100%')
    .height("100%")
  }
}

2.弹窗ui

import { SelectRegionComponent } from "./SelectRegionConponent"

// 选择地区
@CustomDialog
export struct CustomDialogExampleSelectRegion {
  controllerSelectRegion?: CustomDialogController
  @Prop changeFontSize: number = 0;
  @State provincesOrMunicipalities: string = 'country'
  @Link selectedRegion: string

  backPrevious() {
    if (this.provincesOrMunicipalities === 'country') {
      this.controllerSelectRegion?.close()
    }
    if (this.provincesOrMunicipalities === 'provinces') {
      this.provincesOrMunicipalities = 'country'
    }
    if (this.provincesOrMunicipalities === 'city') {
      this.provincesOrMunicipalities = 'provinces'
    }
    if (this.provincesOrMunicipalities === 'district') {
      this.provincesOrMunicipalities = 'city'
    }
  }

  isSelectedRegionFn(area: string) {
    this.selectedRegion = area
    this.controllerSelectRegion?.close()
  }

  build() {
    Column() {
      Row() {
        Row() {
          Text('上一级').fontSize(22)
        }.width('33.33%')
      }.width('100%').margin({ left: 20, bottom: 10 }).justifyContent(FlexAlign.SpaceBetween).onClick(() => {
        this.backPrevious()
      })

      SelectRegionComponent({
        provincesOrMunicipalities: this.provincesOrMunicipalities,
        isSelectedRegionFn: this.isSelectedRegionFn.bind(this)
      }).layoutWeight(1)
    }.width('100%').height('100%')
  }
}

3.弹窗组件ui

import { common } from '@kit.AbilityKit';
import { util } from '@kit.ArkTS';
// 区县
export class DistrictType {
  name: string = '';
  code: string = '';
}

//省或市
export class ProvinceType {
  name: string = '';
  code: string = '';
  districts?: DistrictType[];
}

// 国家
export class CountryType {
  name: string = '';
  subName: string = '';
  provinces?: ProvinceType[];
}
@Component
export struct SelectRegionComponent {
  @State areaData_Country: CountryType[] = [] //国家
  @State areaData_Provinces: ProvinceType[] = [] //省直辖市
  @State areaData_City: ProvinceType[] = [] //市
  @State areaData_District: DistrictType[] = [] //区县
  @Link provincesOrMunicipalities: string
  isSelectedRegionFn: (area: string) => void = (area) => {

  }

  aboutToAppear(): void {
    let context = getContext(this) as common.UIAbilityContext;
    let resourceManager = context.resourceManager;
    resourceManager.getRawFileContent("area.json").then(value => {
      let rawFile = value;
      let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM: true })
      let retStr = textDecoder.decodeWithStream(rawFile, { stream: false });
      this.areaData_Country = JSON.parse(retStr)
      this.areaData_Provinces = this.areaData_Country[1].provinces as ProvinceType[]
    })
  }

  getFullPath_City(districtCode: string) {
    for (const country of this.areaData_Country) {
      const countryName = country.name; // 中国
      for (const province of (country.provinces as ProvinceType[])) {
        const provinceName = province.name; // 北京市
        for (const district of (province.districts as DistrictType[])) {
          if (district.code === districtCode) {
            return `${countryName} ${provinceName} ${district.name}`; // 返回完整路径
          }
        }
      }
    }
    return null; // 如果没有找到
  }

  getFullPath_Other(districtCode: string) {
    if (!this.areaData_Country || this.areaData_Country.length === 0) {
      return null; // 检查数据是否为空
    }
    // 遍历国家列表
    for (const country of this.areaData_Country) {
      const countryName = country.name; // 获取国家名称
      if (!country.provinces || country.provinces.length === 0) {
        continue; // 检查省是否存在
      }
      // 遍历省份列表
      for (const province of country.provinces) {
        const provinceName = province.name; // 获取省份名称
        if (!province.districts || province.districts.length === 0) {
          continue; // 检查城市是否存在
        }
        // 遍历城市列表
        for (const city of province.districts) {
          const cityName = city.name; // 获取城市名称
          if (!(city as ProvinceType).districts || ((city as ProvinceType).districts as DistrictType[]).length === 0) {
            continue; // 检查区是否存在
          }
          // 遍历区县列表
          for (const district of ((city as ProvinceType).districts as DistrictType[])) {
            if (district.code === districtCode) {
              // 找到匹配的区,返回完整路径
              return `${countryName} ${provinceName} ${cityName} ${district.name}`;
            }
          }
        }
      }
    }
    return null; // 如果没有找到匹配的区县,返回 null
  }

  ConfirmRegion(item: CountryType | ProvinceType | DistrictType) {
    if ((item as CountryType).provinces?.length === 0 || (item as ProvinceType).districts?.length === 0) {
      this.isSelectedRegionFn(item.name)
      return
    }
    if ((item as CountryType).provinces?.length !== 0 || (item as ProvinceType).districts?.length !== 0) {

      if (this.provincesOrMunicipalities === 'district') {
        const area = this.getFullPath_Other((item as DistrictType).code)
        this.isSelectedRegionFn(area as string)
      }

      if (this.provincesOrMunicipalities === 'city') {
        if ((item as DistrictType).code.includes("110") || (item as DistrictType).code.includes("120") ||
        (item as DistrictType).code.includes("310") || (item as DistrictType).code.includes("500")) {
          const area = this.getFullPath_City((item as DistrictType).code)
          this.isSelectedRegionFn(area as string)

          return
        }
        this.provincesOrMunicipalities = 'district'
        this.areaData_District = (item as ProvinceType).districts as DistrictType[]

      }
      if (this.provincesOrMunicipalities === 'provinces') {
        this.provincesOrMunicipalities = 'city'
        this.areaData_City = (item as ProvinceType).districts as ProvinceType[]
      }
      if (this.provincesOrMunicipalities === 'country') {
        this.provincesOrMunicipalities = 'provinces'
      }
    }
  }

  @Builder
  areaListBuilder(item: CountryType | ProvinceType | DistrictType) {
    Text(item.name)
      .height(50)
      .width('100%')
      .border({ width: { bottom: 1 }, color: "#cccccc" })
      .margin({ left: 20 })
      .onClick(() => {
        this.ConfirmRegion(item)
      })
  }

  build() {
    Column() {
      List() {
        ForEach(this.provincesOrMunicipalities === 'country' ? this.areaData_Country :
          this.provincesOrMunicipalities === 'provinces' ? this.areaData_Provinces :
            this.provincesOrMunicipalities === 'city' ? this.areaData_City : this.areaData_District,
          (item: CountryType | ProvinceType | DistrictType, i: number) => {
            ListItem() {
              this.areaListBuilder(item)
            }
          })
      }
    }.width('100%').height('100%')
  }
}

注意!!!!图中的数据来自于rawfile文件下的json文件

文件地址:世界国家地区,以及省市区-CSDN博客

世界国家地区,以及省市区资源-CSDN文库,,想给大家免费下载,但是不知道怎么弄,知道方法的朋友可以分享一下,


http://www.kler.cn/a/508701.html

相关文章:

  • mysql 与Redis 数据强一致方案
  • SDL2基本的绘制流程与步骤
  • K8S开启/关闭审计日志
  • 【Go】Go数据类型详解—指针
  • Java21 正则表达式
  • C语言的语法糖
  • 归子莫的科技周刊#1:一周是一年的2%
  • 4.Spring AI Prompt:与大模型进行有效沟通
  • 利用Ai,帮我完善了UsbCamera App的几个界面和设置功能
  • 【蓝桥杯选拔赛真题63】C++奇数 第十四届蓝桥杯青少年创意编程大赛 算法思维 C++编程选拔赛真题解
  • 位运算练习
  • 光谱相机如何还原色彩
  • Axios封装一款前端项目网络请求实用插件
  • 2024年博客之星年度评选—创作影响力评审入围名单公布
  • WINFORM - DevExpress -> alertControl1提示信息框
  • T-SQL语言的计算机基础
  • git 常用命令 git revert
  • 音频可视化小工具
  • 网络安全 | 什么是正向代理和反向代理?
  • Ubuntu20.4和docker终端指令、安装Go环境、安装搜狗输入法、安装WPS2019:保姆级图文详解
  • 开源AI智能名片2+1链动模式S2B2C商城小程序在ABM漏斗中的应用探索
  • Open3D计算点云粗糙度(方法一)【2025最新版】
  • Electron的应用安全测试基础 | 安装与检测基于Electron的应用程序
  • Visual Studio环境搭建Qgis二次开发环境
  • 结合帧级边界检测和深度伪造检测,定位部分伪造音频攻击中的篡改区域
  • 【深度学习量化交易14】正式开源!看海量化交易系统——基于miniQMT的量化交易软件