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: stringbackPrevious() {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 = areathis.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: stringisSelectedRegionFn: (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'}}}@BuilderareaListBuilder(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文库,,想给大家免费下载,但是不知道怎么弄,知道方法的朋友可以分享一下,