介紹

本示例介紹如何使用bindSheet,changeIndex,onAreaChange實現帶切換動效的自定義地址選擇組件。

效果圖預覽

HarmonyOS應用開發:自定義地址選擇組件_鴻蒙開發

使用説明

  1. 進入頁面,點擊場景一中“所在地區”一欄,可拉起省市區的地址選擇彈窗。選擇完區後,彈窗自動關閉,“所在地區”一欄顯示當前選擇的省市區名。
  2. 進入頁面,點擊場景二中的'獲取地址信息'按鈕,可以查看省市區名和相應的id。點擊“所在地區”一欄,在拉起的地址選擇彈窗裏選擇另一個省市區後,再次點擊'獲取地址信息'按鈕,會顯示最新選擇的省市區的信息。

實現思路

使用getRawFileContentSync從rawfile目錄下讀取省市區json文件數據,使用util.TextDecoder進行解碼。

getAddressData(): Array<Province> {
  // 從rawfile本地json文件中獲取數據
  const value = getContext().resourceManager.getRawFileContentSync(this.jsonFileDir);
  // 解碼為utf-8格式
  const textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM: true });
  const textDecoderResult = textDecoder.decodeToString(new Uint8Array(value.buffer));
  const jsonObj: JsonObjType = JSON.parse(textDecoderResult) as JsonObjType;
  const modelBuckets: Array<Province> = [];
  // 映射json數據為model對象
  const modelObj = jsonObj.addressList;
  for (let i = 0; i < modelObj.length; i++) {
  const contactTemp = new Province(modelObj[i].code, modelObj[i].name, modelObj[i].children);
  // 從json中讀取每個省數據寫入modelBuckets
  modelBuckets.push(contactTemp);
}
return modelBuckets;
}
  1. 使用bindSheet綁定地址選擇半模態彈窗頁面。
Row() {
  // ...
}
.width($r('app.string.custom_address_picker_full_size'))
.height($r('app.float.custom_address_picker_size_forty_eight'))
.onClick(() => {
  // 顯示地址選擇半模態彈窗頁面
  this.isShow = true;
  this.currentIndex = AddressType.Province;
})
.bindSheet($$this.isShow, this.addressSelectPage(), {
  height: $r('app.string.custom_address_picker_percent_seventy'), // 半模態彈窗高度
  showClose: false, // 設置不顯示自帶的關閉圖標
  dragBar: false,
  onDisappear: () => {
    // 退出地址選擇半模態彈窗頁面時,重置相關參數
    this.animationDuration = 0;
    // 如果當前省市區沒選全,則清空當前選擇的地址信息
    if (this.currentSelectInfo.region === '') {
      this.currentSelectInfo.provinceId = '';
      this.currentSelectInfo.cityId = '';
      this.currentSelectInfo.regionId = '';
      this.currentSelectInfo.province = '';
      this.currentSelectInfo.city = '';
      this.currentSelectInfo.region = '';
      this.cityList = [];
      this.regionList = [];
    }
  }
})
  1. 使用changeIndex控制省市區列表TabContent切換。使用組件區域變化回調onAreaChange獲取選擇的省市區Text組件寬度,存入textInfos數組,用於後續計算選擇省市區名後下方下滑線動畫水平偏移量leftMargin。
Text(`${params.name === '' ? '請選擇' : params.name} `)
  .height($r('app.string.custom_address_picker_full_size'))
  .fontSize($r('app.float.custom_address_picker_size_sixteen'))
  .fontWeight(this.currentIndex === params.index ? Constants.FONT_WEIGHT_FIVE_HUNDRED :
  Constants.FONT_WEIGHT_FOUR_HUNDRED)
  .fontColor(this.currentIndex === params.index ? $r('app.color.custom_address_picker_font_color_black') :
  $r('app.color.custom_address_picker_font_color_gray'))
  .constraintSize({ maxWidth: 'calc(33%)' })
  .textOverflow({ overflow: TextOverflow.Ellipsis })
  .maxLines(Constants.SIZE_ONE)
  .onClick(() => {
    // 使用changeIndex控制省市區列表TabContent切換
    this.controller.changeIndex(params.index);
  })
  .id(params.index.toString())
  .onAreaChange((oldValue: Area, newValue: Area) => {
    // 使用組件區域變化回調onAreaChange獲取選擇的省市區Text組件寬度,存入textInfos數組,用於後續計算選擇省市區名後下方下滑線動畫水平偏移量leftMargin
    // 組件區域變化時獲取當前Text的寬度newValue.width和x軸相對位置newValue.position.x
    this.textInfos[params.index] = [newValue.position.x as number, newValue.width as number];
    if (this.currentIndex === params.index && params.index === AddressType.Province) {
      // 計算選擇的省市區名下方的下滑線偏移量
      this.leftMargin = (this.textInfos[this.currentIndex][1] - Constants.DIVIDER_WIDTH) / 2;
    }
  })
  1. 在選擇完區名後,使用JSON.parse(JSON.stringify(xxx))深拷貝選擇的省市區數據,用於後續操作中需要加載上一次選擇的完整省市區數據。
List() {
  ForEach(this.regionList, (item: CommonAddressList) => {
    ListItem() {
      this.areaNameItem(AddressType.Region, item)
    }.onClick(() => {
      // 記錄選擇的區信息
      this.currentSelectInfo.regionId = item.code;
      this.currentSelectInfo.region = item.name;
      this.provinceCityRegion =
        this.currentSelectInfo.province + this.currentSelectInfo.city + this.currentSelectInfo.region;
      // 選擇區後,退出地址選擇半模態彈窗頁面
      this.isShow = false;
      // 將當前選中省市區信息保存到lastSelectInfo
      this.lastSelectInfo.provinceId = this.currentSelectInfo.provinceId;
      this.lastSelectInfo.province = this.currentSelectInfo.province;
      this.lastSelectInfo.cityId = this.currentSelectInfo.cityId;
      this.lastSelectInfo.city = this.currentSelectInfo.city;
      this.lastSelectInfo.regionId = this.currentSelectInfo.regionId;
      this.lastSelectInfo.region = this.currentSelectInfo.region;
      // TODO 知識點:在選擇完區名後,使用JSON.parse(JSON.stringify(xxx))深拷貝選擇的省市區數據,用於後續操作中需要加載上一次選擇的完整省市區數據
      // 深拷貝保存到相應的變量中
      this.lastCityList = JSON.parse(JSON.stringify(this.cityList));
      this.lastRegionList = JSON.parse(JSON.stringify(this.regionList));
      this.address = JSON.parse(JSON.stringify(this.lastSelectInfo));
    })
  }, (item: CommonAddressList) => JSON.stringify(item))
}

總結:

本示例中如果當前點擊選擇的省或者市與之前選擇一樣,則跳過省、市數據獲取,直接調用changeIndex(AddressType.City)切換到下一級地區列表,減少冗餘查詢以提升性能。


如果您想系統深入地學習 HarmonyOS 開發或想考取HarmonyOS認證證書,歡迎加入華為開發者學堂:

請點擊→:  HarmonyOS官方認證培訓

HarmonyOS應用開發:自定義地址選擇組件_HarmonyOS_02