DEV Community

Cover image for Landscape-Portrait Switch Animation, Time-Date Functions, Tabs, Routing Return Listening, String Issues
kouwei qing
kouwei qing

Posted on

Landscape-Portrait Switch Animation, Time-Date Functions, Tabs, Routing Return Listening, String Issues

[Daily HarmonyOS Next Knowledge] Landscape-Portrait Switch Animation, Time-Date Functions, Tabs, Routing Return Listening, String Issues

1. How to listen for the callback when the landscape-portrait animation ends in HarmonyOS?

To set landscape-portrait switching, use setPreferredOrientation: https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-window-V5

Windows provide basic capabilities for managing windows, including creation, destruction, attribute settings, and scheduling between windows.

The module offers the following common window-related functions:

  • Window: The current window instance, the basic unit managed by the window manager.
  • WindowStage: The window manager, responsible for managing each basic window unit.

2. When creating a Date class in HarmonyOS and passing in year-month-day-hour-minute-second, why does converting the millisecond value obtained via getTime() back to year-month-day yield different results?

The obtained date is a timestamp. During conversion, it defaults to foreign time, which may differ from domestic time (e.g., month differences). Adjustments like addition/subtraction are needed.

Demo for converting date to time:

class Opt {
  yy: string = '';
  mm: string = '';
  dd: string = '';
  HH: string = '';
  MM: string = '';
  SS: string = '';
}
@Entry
@Component
struct TimePage {
  @State message: number = 1622422400000;
  formatDate(timestamp: number, format = 'yyyy-mm-dd') {
    let res = "";
    try {
      const date = new Date(timestamp);
      const opt: Opt = {
        yy: date.getFullYear().toString(),
        mm: (date.getMonth() + 1).toString(),
        dd: date.getDate().toString(),
        HH: date.getHours().toString(),
        MM: date.getMinutes().toString(),
        SS: date.getSeconds().toString(),
      };
      const regKeys: string[] = ['y+', 'm+', 'd+', 'H+', 'M+', 'S+'];
      for (let i = 0; i < regKeys.length; i++) {
        const regKey = regKeys[i];
        const reg = new RegExp(regKey);
        let ret = reg.exec(format);
        if (ret) {
          switch (regKey) {
            case 'y+':
              format = format.replace(reg, ret.length === 1 ? opt.yy : opt.yy.padStart(ret.length, "0"));
            case 'm+':
              format = format.replace(reg, ret.length === 1 ? opt.mm : opt.mm.padStart(ret.length, "0"));
            case 'd+':
              format = format.replace(reg, ret.length === 1 ? opt.dd : opt.dd.padStart(ret.length, "0"));
            case 'H+':
              format = format.replace(reg, ret.length === 1 ? opt.HH : opt.HH.padStart(ret.length, "0"));
            case 'M+':
              format = format.replace(reg, ret.length === 1 ? opt.MM : opt.MM.padStart(ret.length, "0"));
            case 'S+':
              format = format.replace(reg, ret.length === 1 ? opt.SS : opt.SS.padStart(ret.length, "0"));
          }
        }
      }
      res = format;
    } catch (error) {
      console.error("ERROR formatDate" + error);
    }
    return res;
  }
  build() {
    Row() {
      Column() {
        Text(this.formatDate(new Date(this.message).valueOf(),'yyyy/mm/dd HH:MM:SS')).fontSize(30)
      }
      .width('100%')
    }
    .height('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

Reference documentation for the third-party library dayjs: https://ohpm.openharmony.cn/#/cn/detail/dayjs

3. How to set the font color and tabBar color of the Tabs component in HarmonyOS?

To set the font color, use a custom navigation bar. Reference: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-navigation-tabs-V5#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%AF%BC%E8%88%AA%E6%A0%8F

The bottom navigation bar, typically used to distinguish main page functions, combines text and semantic icons for better user experience. In such cases, customizing the navigation tab style is required.

![[Pasted image 20250310001146.png]]

By default, the system uses an underline to mark the active tab, while custom navigation bars must implement styles to distinguish active and inactive tabs.

Custom navigation bars are set via the tabBar parameter using a CustomBuilder-supported custom function component. For example, declare a custom function component tabBuilder that accepts parameters including tab text title, index targetIndex, and image resources for selected/normal states. The UI style is determined by matching currentIndex (active index) with targetIndex (tab index).

@State currentIndex: number = 0;

@Builder tabBuilder(title: string, targetIndex: number, selectedImg: Resource, normalImg: Resource) {
  Column() {
    Image(this.currentIndex === targetIndex ? selectedImg : normalImg)
      .size({ width: 25, height: 25 })
    Text(title)
      .fontColor(this.currentIndex === targetIndex ? '#1698CE' : '#6B6B6B')
  }
  .width('100%')
  .height(50)
  .justifyContent(FlexAlign.Center)
}
Enter fullscreen mode Exit fullscreen mode

Demo:

@Entry
@Component
struct TabsExample1 {
  @State currentIndex: number = 2

  @Builder tabBuilder(title: string, targetIndex: number) {
    Column() {
      Text(title)
        .fontColor(this.currentIndex === targetIndex ? '#FF0000' : '#00FF00')
    }
  }

  build() {
    Column() {
      Tabs({ barPosition: BarPosition.End }) {
        TabContent() {

        }.tabBar(this.tabBuilder('Home', 0))

        TabContent() {

        }.tabBar(this.tabBuilder('Discover', 1))

        TabContent() {

        }.tabBar(this.tabBuilder('Recommend', 2))

        TabContent() {

        }.tabBar(this.tabBuilder('Mine', 3))
      }
      .animationDuration(0)
      .backgroundColor('#F1F3F5')
      .onChange((index: number) => {
        this.currentIndex = index
      })
    }.width('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

4. Does HarmonyOS Navigation support routing return listening similar to Flutter?

Navigation supports return listening via onBackPressed. Refer to the official example: https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-basic-components-navigation-V5

The Navigation component is the root view container for routing, typically used as the root container of a Page. It internally includes a title bar, content area, and toolbar by default. The content area displays navigation content (Navigation's child components) on the home page or NavDestination's child components on non-home pages, with switching via routing.

5. How to determine if a character in a HarmonyOS string is an alphabet, Chinese character, or number?

str = "AB汉字123nb"
for (let i = 0; i < str.length; i++) {
  const c = str.charAt(i)
}
Enter fullscreen mode Exit fullscreen mode

Use charCodeAt() to convert each character to its ASCII value, then determine the type by comparing it with the ASCII range of alphabets, Chinese characters, and numbers.

Top comments (0)