根据地区名字开头首字母选择地区

根据地区名字开头的首字母,按开头字母展示地区,并可选择对应的地区。

HarmonyOS
2024-05-26 10:58:18
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
易安安安

使用的核心API

List

ListItemGroup

核心代码解释

/* 
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved. 
 */ 
import I18n from '@ohos.i18n'; 
import Intl from '@ohos.intl'; 
import UIAbility from '@ohos.app.ability.UIAbility'; 
import buffer from '@ohos.buffer'; 
import { RegionRequestData } from './RegionRequestData'; 
import { RegionData } from './RegionData'; 
import { RegionDataGroups } from './RegionDataGroups'; 
import display from '@ohos.display'; 
  
// import { display } from '@kit.ArkUI'; 
  
  
// const logger: Logger = new Logger("TelCountryChoosePanel") 
  
let collator = new Intl.Collator(I18n.System.getSystemLocale(), { 
  usage: 'sort', 
  collation: 'pinyin', 
  caseFirst: 'lower' 
}) 
  
let data1 = '{\"code\":\"0\",\"lstRegionInfo\":[[{\"id\":3510,\"name\":\"北京\"},{\"id\":3511,\"name\":\"安徽\"},{\"id\":3656,\"name\":\"福建\"},{\"id\":3751,\"name\":\"甘肃\"},{\"id\":3853,\"name\":\"广东\"},{\"id\":4035,\"name\":\"广西壮族自治区\"},{\"id\":4158,\"name\":\"贵州\"},{\"id\":4261,\"name\":\"海南\"},{\"id\":4304,\"name\":\"河北\"},{\"id\":4489,\"name\":\"河南\"},{\"id\":4672,\"name\":\"黑龙江\"},{\"id\":4814,\"name\":\"湖北\"},{\"id\":4935,\"name\":\"湖南\"},{\"id\":5073,\"name\":\"吉林\"},{\"id\":5147,\"name\":\"江苏\"},{\"id\":5285,\"name\":\"江西\"},{\"id\":5399,\"name\":\"辽宁\"},{\"id\":5516,\"name\":\"内蒙古自治区\"},{\"id\":5630,\"name\":\"宁夏回族自治区\"},{\"id\":5662,\"name\":\"青海\"},{\"id\":5714,\"name\":\"山东\"},{\"id\":5873,\"name\":\"山西\"},{\"id\":6008,\"name\":\"陕西\"},{\"id\":6126,\"name\":\"上海\"},{\"id\":6147,\"name\":\"四川\"},{\"id\":6349,\"name\":\"天津\"},{\"id\":6370,\"name\":\"西藏自治区\"},{\"id\":6451,\"name\":\"新疆维吾尔自治区\"},{\"id\":6565,\"name\":\"云南\"},{\"id\":6711,\"name\":\"浙江\"},{\"id\":6819,\"name\":\"重庆\"}]],\"lstRegionTree\":[],\"success\":true}'; 
let data2 = '{\"code\":\"0\",\"regionInfos\":[{\"code\":\"0\",\"id\":3530,\"leaf\":false,\"name\":\"安庆\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":3542,\"leaf\":false,\"name\":\"蚌埠\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":3556,\"leaf\":false,\"name\":\"池州\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":3561,\"leaf\":false,\"name\":\"滁州\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":3570,\"leaf\":false,\"name\":\"阜阳\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":3583,\"leaf\":false,\"name\":\"淮北\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":3588,\"leaf\":false,\"name\":\"淮南\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":3595,\"leaf\":false,\"name\":\"黄山\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":3603,\"leaf\":false,\"name\":\"六安\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":3611,\"leaf\":false,\"name\":\"马鞍山\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":3616,\"leaf\":false,\"name\":\"宿州\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":3622,\"leaf\":false,\"name\":\"铜陵\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":3627,\"leaf\":false,\"name\":\"芜湖\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":3635,\"leaf\":false,\"name\":\"宣城\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":3643,\"leaf\":false,\"name\":\"亳州\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":3648,\"leaf\":false,\"name\":\"合肥\",\"parentId\":3511,\"parentNumberCode\":\"3511!\",\"status\":\"1\"}],\"success\":true}'; 
let data3 = '{\"code\":\"0\",\"regionInfos\":[{\"code\":\"0\",\"id\":7532,\"leaf\":false,\"name\":\"蚌山区\",\"parentId\":3542,\"parentNumberCode\":\"3511!3542!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":7533,\"leaf\":false,\"name\":\"龙子湖区\",\"parentId\":3542,\"parentNumberCode\":\"3511!3542!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":7534,\"leaf\":false,\"name\":\"禹会区\",\"parentId\":3542,\"parentNumberCode\":\"3511!3542!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":7535,\"leaf\":false,\"name\":\"淮上区\",\"parentId\":3542,\"parentNumberCode\":\"3511!3542!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":7536,\"leaf\":false,\"name\":\"怀远县\",\"parentId\":3542,\"parentNumberCode\":\"3511!3542!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":7537,\"leaf\":false,\"name\":\"五河县\",\"parentId\":3542,\"parentNumberCode\":\"3511!3542!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":7538,\"leaf\":false,\"name\":\"固镇县\",\"parentId\":3542,\"parentNumberCode\":\"3511!3542!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":139619,\"leaf\":false,\"name\":\"蚌埠市经济开发区\",\"parentId\":3542,\"parentNumberCode\":\"3511!3542!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":139625,\"leaf\":false,\"name\":\"蚌埠市高新技术开发区\",\"parentId\":3542,\"parentNumberCode\":\"3511!3542!\",\"status\":\"1\"},{\"code\":\"0\",\"id\":129665,\"leaf\":false,\"name\":\"-\",\"parentId\":3542,\"parentNumberCode\":\"3511!3542!\",\"status\":\"1\"}],\"success\":true}'; 
  
@Entry 
@Component 
export struct SelectRegionPage { 
  storage: LocalStorage = LocalStorage.GetShared() 
  @State alphabetSelected: number = 0 
  @State showPopup: boolean = false 
  public countriesList: Array<Array<string>> = new Array() 
  private controller: SearchController = new SearchController(); 
  private indexMap: Map<string, number> = new Map() 
  private indexList: Array<string> = new Array() 
  private countryGroup: Array<Array<Array<string>>> = new Array() 
  @State countriesForShow: Array<Array<Array<string>>> = new Array() 
  private indexUtil = I18n.getInstance(I18n.System.getSystemLocale()); 
  private scroller: Scroller = new Scroller() 
  @LocalStorageLink('isPanelCenter') isPanelCenter: boolean = false 
  @LocalStorageLink('isFullPage') isFullPage: boolean = true 
  @LocalStorageLink('isLandScape') isLandScape?: boolean = false; 
  private normalIndexValue: string[] = ['#', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 
    'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] 
  private landScapeIndexValue: string[] = ['#', 'A', '·', 'G', '·', 'M', '·', 'S', '·', 'Z'] 
  private panelParam: string = ''; 
  @State regionInfo: Array<RegionData> = []; 
  @State regionDataGroupsList: Array<RegionDataGroups> = []; 
  @State selectRegionPath: string = ""; 
  @State selectedRegion: string = ""; 
  @State selectState: boolean = true; 
  private fixedText: string = "请选择"; 
  private noSelect: string = "暂不选择" 
  @State topVp: number = 0; 
  
  getData(name: string) { 
  
    if (name === 'data1') { 
      return JSON.parse(data1) as RegionRequestData; 
    } 
    if (name === 'data2') { 
      return JSON.parse(data2) as RegionRequestData; 
    } 
    if (name === 'data3') { 
      return JSON.parse(data3) as RegionRequestData; 
    } 
  
    return new RegionRequestData(); 
  } 
  
  private onClickPointIndex(indexList: string[], beforeWord: string, afterWord: string): number { 
    for (let i = 1; i < indexList.length; i++) { 
      if (indexList[i] > beforeWord && indexList[i] < afterWord) { 
        return i; 
      } 
    } 
    return 0; 
  } 
  
  private onSlideList(indexList: string[], target: string): number { 
    for (let i = 1; i < indexList.length; i++) { 
      if (indexList[i] > target && indexList[i] != '·') { 
        return i; 
      } 
    } 
    return 0; 
  } 
  
  private searchIndex(indexList: string[], target: string): number { 
    return indexList.indexOf(target); 
  } 
  
  private collationData(regionRequestData: RegionRequestData, isProvinceRegion: boolean) { 
  
    let regionDatas = isProvinceRegion ? regionRequestData.lstRegionInfo[0] : regionRequestData.regionInfos 
  
    this.regionInfo = regionDatas.map((regionData: RegionData) => { 
      if (regionData.name === '-') { 
        regionData.name = this.noSelect; 
      } 
      return regionData; 
    }).sort((a, b) => collator.compare(a.name, b.name)); 
    // todo 暂无数据处理 
    this.indexList = []; 
    this.regionDataGroupsList = []; 
    this.regionInfo.forEach((value: RegionData) => { 
      let index = this.indexUtil.getIndex(value.name); 
  
      if (this.indexList.indexOf(index) === -1) { 
        let regionDataGroups: RegionDataGroups = new RegionDataGroups(); 
        regionDataGroups.title = index; 
        this.indexList.push(index); 
        regionDataGroups.regionDataList.push(value); 
        this.regionDataGroupsList.push(regionDataGroups); 
      } else { 
        this.regionDataGroupsList[this.indexList.indexOf(index)].regionDataList.push(value); 
      } 
    }) 
    this.selectState = true; 
    if (!isProvinceRegion && this.selectedRegion) { 
      this.selectRegionPath = this.selectRegionPath + this.selectedRegion + ' > ' 
    } 
  } 
  
  aboutToAppear() { 
    // todo aboutToAppear日志 
    let regionData1 = this.getData('data1'); 
    if (regionData1.lstRegionInfo.length == 0 || regionData1.lstRegionInfo[0].length == 0) { 
      // todo 弹框+提示 
      return; 
    } 
    this.collationData(regionData1, true); 
  
  
    // 
    console.log("regionDataGroups:" + JSON.stringify(this.regionDataGroupsList)); 
  
  } 
  
  aboutToDisappear(): void { 
  } 
  
  @Builder 
  buildToolbar() { 
    Row() { 
      Row() { 
        Stack() { 
          Image($r("app.media.hwid_ic_back")) 
            .width(24) 
            .height(24) 
            .margin({ top: 8, left: 8 }) 
            .fillColor($r('sys.color.ohos_id_color_primary')) 
            .id('img_hwid_select_region_back') 
          Column() { 
          } 
          .width(40) 
          .height(40) 
          .opacity(0.1) 
          .onClick(() => { // 关闭panel 
  
            this.showPopup = false 
          }) 
        } 
        .alignContent(Alignment.TopStart) 
        .height('100%') 
  
        Text($r('app.string.hwid_select_region')) 
          .id('text_hwid_select_region_title') 
          .alignSelf(ItemAlign.End) 
          .margin({ bottom: 12, left: 8 }) 
          .fontSize($r('sys.float.ohos_id_text_size_headline8')) 
          .fontWeight(FontWeight.Medium) 
          .fontFamily($r('sys.string.ohos_id_text_font_family_medium')) 
      } 
      .margin({ top: 12, left: 12 }) 
  
      Row() { 
        Stack() { 
          Image($r("app.media.hwid_ic_cancel")) 
            .width(24) 
            .height(24) 
            .fillColor($r("sys.color.ohos_id_color_foreground")) 
            .focusable(true) 
            .margin({ top: 8, right: 8 }) 
            .id("img_hwid_select_region_close") 
          Column() { 
          } 
          .width(40) 
          .height(40) 
          .opacity(0.1) 
          .onClick(() => { // 关闭panel 
            this.showPopup = false 
          }) 
        } 
        .height('100%') 
        .alignContent(Alignment.TopEnd) 
      } 
      .margin({ right: 12, top: 12 }) 
    } 
    .justifyContent(FlexAlign.SpaceBetween) 
    .height(56) 
    .width('100%') 
  } 
  
  @Builder 
  itemHead(text: string) { 
    ListItem() { 
      Row() { 
        Text(text) 
          .fontSize($r('sys.float.ohos_id_text_size_sub_title3')) 
          .fontWeight(FontWeight.Medium) 
          .fontFamily($r('sys.string.ohos_id_text_font_family_medium')) 
          .fontColor($r('sys.color.ohos_id_color_text_secondary')) 
      } 
      .alignItems(VerticalAlign.Bottom) 
      .justifyContent(FlexAlign.Start) 
      .backgroundColor($r('sys.color.ohos_id_color_panel_bg')) 
      .enabled(this.selectState) 
      .height(48) 
      .width('100%') 
      .padding({ left: 12, right: 12 }) 
      .backgroundImageSize(ImageSize.Auto) 
    } 
  } 
  
  build() { 
    NavDestination() { 
      Column() { 
        this.buildToolbar() 
        Column() { 
          Row() { 
            Text() { 
              Span(this.selectRegionPath) 
                .fontColor($r('sys.color.ohos_id_color_text_secondary')) 
                .fontSize($r('sys.float.ohos_id_text_size_body2')) 
                .fontWeight(FontWeight.Medium) 
                .fontFamily($r('sys.string.ohos_id_text_font_family_medium')) 
                .id("text_hwid_select_region_selectRegionPath") 
  
              Span(this.fixedText) 
                .fontColor($r('sys.color.ohos_id_color_text_primary_activated')) 
                .fontSize($r('sys.float.ohos_id_text_size_body2')) 
                .fontWeight(FontWeight.Medium) 
                .fontFamily($r('sys.string.ohos_id_text_font_family_medium')) 
                .id("text_hwid_select_region_fixedText") 
            } 
          } 
          .width('100%') 
          .padding({ right: 12, left: 12 }) 
  
  
          Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceAround }) { 
            Column() { 
              List({ scroller: this.scroller, space: 0, initialIndex: 0 }) { 
                ForEach(this.regionDataGroupsList, (regionDataGroups: RegionDataGroups, index) => { 
  
                  ListItemGroup({ header: this.itemHead(regionDataGroups.title)}) { 
                    ListItem() { 
                      List() { 
                        ForEach(regionDataGroups.regionDataList, (regionData: RegionData, index?: number) => { 
                          ListItem({ style: ListItemStyle.CARD }) { 
                            Row() { 
                              Text(regionData.name) 
                                .fontSize($r('sys.float.ohos_id_text_size_body1')) 
                                .fontWeight(FontWeight.Medium) 
                                .fontFamily($r('sys.string.ohos_id_text_font_family_medium')) 
                                .fontColor($r('sys.color.ohos_id_color_text_primary')) 
                                .id("text_hwid_select_region_value_" + regionData.name) 
                              LoadingProgress() 
                                .id("icon_hwid_region_selected") 
                                .width(24) 
                                .height(24) 
                                .id("text_hwid_select_region_loading_" + regionData.name) 
                            } 
                            .alignItems(VerticalAlign.Center) 
                            .justifyContent(FlexAlign.SpaceBetween) 
                            .height(48) 
                            .width('100%') 
                          } 
                          .enabled(this.selectState) 
                          .width('100%') 
                          .align(Alignment.BottomStart) 
                          .height(48) 
                          .onClick(() => { 
                            // 暂不选择需要退出 
                            if (regionData.name === this.noSelect) { 
                              this.selectedRegion = ''; 
                              // 页面返回 
                              return; 
                            } 
                            this.selectedRegion = regionData.name; 
                            this.selectState = false; 
  
                            let regionData1 = this.getData('data3'); 
                            if (regionData1.regionInfos.length == 0) { 
                              // todo 弹框+提示 
                              return; 
                            } 
                            this.collationData(regionData1, false); 
  
                          }) 
                        }) 
                      } 
                      .divider({ 
                        strokeWidth: 0.5, 
                        color: $r('sys.color.ohos_id_color_list_separator'), 
                        startMargin: 12, 
                        endMargin: 12 
                      }) 
                      .width('100%') 
  
                    } 
                    .backgroundColor($r('sys.color.ohos_id_color_card_bg')) 
                    .borderRadius($r('sys.float.ohos_id_corner_radius_notification')) 
                    .width('100%') 
                    .padding(4) 
  
                  } 
                  .layoutWeight(1) 
                  .borderRadius($r('sys.float.ohos_id_corner_radius_notification')) 
                  .backgroundColor("#00000000") 
                  .align(Alignment.Center) 
                  .margin({ top: '0.00px', right: '0', bottom: '0.00px', left: '12.00vp' }) 
                }) 
                ListItem() { 
                } 
                .height(24) 
              } 
              .sticky(StickyStyle.Header) 
              .onScrollIndex((start: number, end: number) => { 
                let target = this.indexList[start] 
                let indexList = this.isLandScape ? this.landScapeIndexValue : this.normalIndexValue; 
                let index = this.searchIndex(indexList, target) 
                this.alphabetSelected = index === -1 ? this.onSlideList(indexList, target) - 1 : index; 
                // todo 
                console.log("start:" + start + " alphabetSelected: " + this.alphabetSelected) 
              }) 
              .width('100%') 
              .scrollBar(BarState.Off) 
  
              // .edgeEffect(EdgeEffect.None) 
            } 
  
            Column() { 
              AlphabetIndexer({ 
                arrayValue: this.isLandScape ? this.landScapeIndexValue : this.normalIndexValue, 
                selected: 0 
              }) 
                .usingPopup(false) 
                .selected(this.alphabetSelected) 
                .onSelect((index: number) => { 
                  if (index === 0) { 
                    this.scroller.scrollToIndex(0); 
                    return; 
                  } 
                  let pos = 0 
                  let useValue = this.isLandScape ? this.landScapeIndexValue : this.normalIndexValue 
                  let currentWord = useValue[index] // 在右侧索引上的位置 
                  if (currentWord == '·') { // 在右侧索引上的位置 刚号是点,则需要找右侧索引上一个字母 
  
                    let beforeWord = useValue[index - 1]; // 这个是右侧索引点的上一个字母 
                    let afterWord = useValue[index + 1]; 
  
                    pos = this.onClickPointIndex(this.indexList, beforeWord, afterWord) 
                  } else { 
                    pos = this.searchIndex(this.indexList, currentWord) 
                  } 
                  if (pos === -1) { 
                    return; 
                  } 
                  console.log("scrollToIndex pos:" + pos); 
                  this.scroller.scrollToIndex(pos); 
                }) 
                .id("id_hwid_region_choose_alphabetIndexer") 
                .onAreaChange((oldValue: Area, newValue: Area) => { 
                  // 获取屏幕对象 
                  let displayObj: display.Display = display.getDefaultDisplaySync(); 
                  // 获取屏幕高度 
                  let displayHeight: number = displayObj.height / displayObj.densityPixels; 
  
                  console.log("displayHeight1111111:" + displayHeight + "  " + newValue.height); 
                }) 
            } 
            .height("100%") 
            .alignItems(HorizontalAlign.Center) 
  
          } 
          .height("100%") 
          .layoutWeight(1) 
        } 
        .layoutWeight(1) 
  
      } 
      .width('100%') 
      .height('100%') 
      .backgroundColor($r('sys.color.ohos_id_color_panel_bg')) 
      .onAreaChange((oldValue: Area, newValue: Area) => { 
        // 获取屏幕对象 
        let displayObj: display.Display = display.getDefaultDisplaySync(); 
        // 获取屏幕高度 
        let displayHeight: number = displayObj.height / displayObj.densityPixels; 
  
        console.log("displayHeight:" + displayHeight + "  " + newValue.height); 
      }) 
    } 
    .onBackPressed(() => { 
  
      this.showPopup = false 
      return true 
    }) 
    .onShown(() => { 
  
    }) 
    .hideTitleBar(true) 
    .backgroundColor(Color.Transparent) 
  } 
}

实现效果

适配版本信息

IDE:DevEco Studio 4.1.1.300

SDK: 4.1.2.1

分享
微博
QQ
微信
回复
2024-05-27 10:39:17
相关问题
HarmonyOS 提取汉字首字母
23浏览 • 1回复 待解决
HarmonyOS 地区选择器多级列表效果
369浏览 • 1回复 待解决
如何获取线程ID和名字
515浏览 • 1回复 待解决
HarmonyOS 如何修改app的名字
328浏览 • 1回复 待解决
HarmonyOS so文件可以改名字吗?
45浏览 • 1回复 待解决
修改module名字后,module未被IDE识别
883浏览 • 1回复 待解决
textOverflow怎么按字母截断
799浏览 • 1回复 待解决
HarmonyOS 修改了APP名字和图标没生效
31浏览 • 1回复 待解决
linux排除带空行和#开头的行
5023浏览 • 1回复 待解决
JSON反序列化,如何重命名字段?
246浏览 • 1回复 待解决