DEV Community

zhonghua
zhonghua

Posted on • Edited on

HarmonyOS Development in Practice: A Detailed Explanation of the Page Management Utility Class in HarmonyOS App Development

HarmonyOS Development in Practice: A Detailed Explanation of the Page Management Utility Class in HarmonyOS App Development

I. Introduction

In the journey of HarmonyOS app development, efficiently managing page layout and display to meet user demands for immersive experiences, personalized StatusBar colors, and other interface features has always been a focal point for developers. To address this, I have specially designed a practical "Page Management Utility Class" that boasts powerful functionalities to help developers easily tackle various page management challenges.

II. Page Management Utility Class: Your Interface Control Tool

The Page Management Utility Class is akin to a professional tool for interface control, offering developers a series of specialized static attributes and methods. With these features, developers can easily obtain key page information, such as the height of the top safe area (status bar height), the height of the bottom safe area, the full-screen development status, and the status bar color. This utility class is undoubtedly an indispensable part of HarmonyOS app development.

III. Core Attributes Revealed

  1. Top Safe Area Height (Status Bar Height)
  • Variable Name: static statusBarHeight: number = 0
  • Interpretation: This attribute helps developers quickly obtain the height of the top safe area, i.e., the status bar height. By understanding the screen space occupied by the status bar, developers can more accurately layout page content to ensure that it is not obscured.
  1. Bottom Safe Area Height
  • Variable Name: static navigationBarHeight: number = 0
  • Interpretation: This attribute represents the height of the bottom safe area, typically corresponding to the navigation bar height. By understanding this value, developers can prevent page content from overlapping with the navigation bar, enhancing user experience.
  1. Full-Screen Development Status
  • Variable Name: static isFullScreenLayout: boolean
  • Interpretation: This attribute is used to determine whether the app is in full-screen development mode. When set to true, the app will ignore system UI elements to achieve a true full-screen effect; when set to false, the app will consider the presence of these UI elements.
  1. Current Status Bar Content Color
  • Variable Name: static statusBarContentColor: string
  • Interpretation: Developers can use this attribute to obtain or set the current status bar content color, ensuring that the status bar is consistent with the overall style of the app, thereby enhancing the visual effect and user experience of the app.
  1. App Main Window
  • Variable Name: static appMainWindow: window.Window
  • Interpretation: This attribute provides a reference to the app's main window, allowing developers to directly access various properties and methods of the main window to achieve precise control and management of the window.

IV. Initialization Method: Easily Start Your Interface Control Journey

The Page Management Utility Class provides an initialization method that allows developers to easily start this utility class by simply passing in the corresponding parameters. During the initialization process, the utility class will automatically obtain the main window object, set the full-screen development status, and calculate the heights of the top and bottom safe areas, providing the basic data for subsequent page layout and management.

V. Collection of Practical Methods

The Page Management Utility Class also offers a series of practical methods, such as setting the transparency of the status bar and adjusting the style of the navigation bar. These methods are not only powerful but also easy to use, helping developers quickly achieve various interface effects.

VI. Key Function Analysis

  1. setWindowLayoutFullScreen(fullScreen: boolean):
  • This method is used to control whether the app window is displayed in full-screen mode.
  • If appMainWindow exists, it calls its setWindowLayoutFullScreen method and passes in the fullScreen parameter.
  1. setStatusBarLightContent and setStatusBarDarkContent:
  • These two methods are used to quickly set the status bar text color to white and black, respectively.
  • In fact, they call the setStatusBarContentColor method and pass in the corresponding color values.
  1. setStatusBarContentColor(color: string):
  • This method is used to set the status bar text color.
  • First, it checks whether the passed-in color is the same as the current statusBarContentColor. If they are the same, it directly returns to avoid unnecessary operations.
  • If the colors are different, it updates the value of statusBarContentColor and calls the appMainWindow's setWindowSystemBarProperties method to set the status bar text color.
  1. setStatusBarColor(color: string):
  • This method is used to set the status bar background color.
  • If appMainWindow exists, it calls its setWindowSystemBarProperties method and passes in the status bar background color.
  1. showStatusBar and hideStatusBar:
  • These two methods are used to display and hide the status bar, respectively.
  • They control the display and hiding of the status bar by calling the appMainWindow's setWindowSystemBarEnable method and passing in the corresponding parameters.

VII. Overall Code Display

import window from '@ohos.window'
import { display } from '@kit.ArkUI'
import { UIUtil } from './UIUtil'

/**
 * About page status bar, etc.
 */
export class LibWindowHelper {
  // Top status bar height
  static statusBarHeight: number = 0;

  // Bottom navigation bar height
  static navigationBarHeight: number = 0;

  // Whether to enable full-screen layout
  static isFullScreenLayout: boolean;

  // Current status bar content color
  static statusBarContentColor: string;

  // App main window object
  static appMainWindow: window.Window;

  // Initialization method
  static initialize(windowStage: window.WindowStage, isFullScreen: boolean) {
    // Obtain the app's main window object
    LibWindowHelper.appMainWindow = windowStage.getMainWindowSync();

    // Set the full-screen layout status
    LibWindowHelper.isFullScreenLayout = isFullScreen;

    // If full-screen layout is enabled, set the window to full-screen mode
    if (LibWindowHelper.isFullScreenLayout) {
      LibWindowHelper.appMainWindow.setWindowLayoutFullScreen(isFullScreen);
    }

    // Obtain the top status bar area and calculate its height
    let avoidAreaTop = LibWindowHelper.appMainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
    LibWindowHelper.statusBarHeight = Number(UIUtil.px2vp(avoidAreaTop.topRect.height).toPrecision(5));

    // Obtain the bottom navigation bar area and calculate its height
    let avoidAreaBottom = LibWindowHelper.appMainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
    LibWindowHelper.navigationBarHeight = Number(UIUtil.px2vp(avoidAreaBottom.bottomRect.height).toPrecision(5));

    // Listen for foldable screen status
    LibWindowHelper.listenDisplayFoldStatus();
  }

  /**
   * Set the app window to full-screen layout
   *
   * @param fullScreen Whether to display in full-screen mode
   */
  static setWindowLayoutFullScreen(fullScreen: boolean) {
    if (LibWindowHelper.appMainWindow) {
      LibWindowHelper.appMainWindow.setWindowLayoutFullScreen(fullScreen);
    }
  }

  /**
   * Set the status bar text color to white
   */
  static setStatusBarLightContent() {
    LibWindowHelper.setStatusBarContentColor('#ffffff');
  }

  /**
   * Set the status bar text color to black
   */
  static setStatusBarDarkContent() {
    LibWindowHelper.setStatusBarContentColor('#000000');
  }

  /**
   * Set the status bar text color
   *
   * @param color Status bar text color
   */
  static setStatusBarContentColor(color: string) {
    // Avoid unnecessary operations; if the color has not changed, return directly
    if (color === LibWindowHelper.statusBarContentColor) {
      return;
    }
    LibWindowHelper.statusBarContentColor = color;
    if (LibWindowHelper.appMainWindow) {
      LibWindowHelper.appMainWindow.setWindowSystemBarProperties({
        statusBarContentColor: LibWindowHelper.statusBarContentColor
      });
    }
  }

  /**
   * Set the status bar background color
   *
   * @param color Status bar background color
   */
  static setStatusBarColor(color: string) {
    if (LibWindowHelper.appMainWindow) {
      LibWindowHelper.appMainWindow.setWindowSystemBarProperties({
        statusBarColor: color
      });
    }
  }

  /**
   * Show the status bar
   */
  static showStatusBar() {
    if (LibWindowHelper.appMainWindow) {
      LibWindowHelper.appMainWindow.setWindowSystemBarEnable(['status', 'navigation']);
    }
  }

  /**
   * Hide the status bar
   */
  static hideStatusBar() {
    if (LibWindowHelper.appMainWindow) {
      LibWindowHelper.appMainWindow.setWindowSystemBarEnable(['navigation']);
    }
  }

}
Enter fullscreen mode Exit fullscreen mode

VIII. Usage Instructions and Precautions for the Utility Class

Usage Instructions

In the EntryAbility.ts file, you can manage page layout and display using the LibWindowHelper utility class by following these steps:

  1. Initialize the Window Helper Tool

After the window stage (windowStage) is created, you need to use this stage to initialize LibWindowHelper. By calling the onWindowStageCreate method and passing in the windowStage parameter, you can obtain a reference to the main window and initialize it using the LibWindowHelper.initialize method.

Example code:

onWindowStageCreate(windowStage: window.WindowStage) {
    windowStage.getMainWindow((err, mainWindow) => {
        if (err) {
            // Handle errors that occur when obtaining the main window
            console.error('Error obtaining the main window:', err);
        } else {
            // Initialize the window helper tool, setting the full-screen display mode to true
            LibWindowHelper.initialize(mainWindow, true);
        }
    });
}
Enter fullscreen mode Exit fullscreen mode
  1. Enable or Disable Full-Screen Display

You can easily enable or disable the app's full-screen display mode by calling the LibWindowHelper.setWindowLayoutFullScreen method. Passing in true will enable full-screen display, while passing in false will disable it.

Example code:

// Enable full-screen display
LibWindowHelper.setWindowLayoutFullScreen(true);

// Disable full-screen display
LibWindowHelper.setWindowLayoutFullScreen(false);
Enter fullscreen mode Exit fullscreen mode
  1. Set the Status Bar Text Color

When the status bar background is dark, you may need to set the status bar text color to dark to improve readability. This can be achieved using the LibWindowHelper.setStatusBarDarkContent method.

Example code:

// Set the status bar text to dark
LibWindowHelper.setStatusBarDarkContent();
Enter fullscreen mode Exit fullscreen mode
  1. Customize the Status Bar Background Color

LibWindowHelper allows you to customize the status bar background color through the setStatusBarColor method. Simply pass in a hexadecimal color code string.

Example code:

// Set the status bar background color to dark gray
LibWindowHelper.setStatusBarColor('#333333');
Enter fullscreen mode Exit fullscreen mode
  1. Control the Display and Hiding of the Status Bar

You can use the showStatusBar and hideStatusBar methods provided by LibWindowHelper to control the display and hiding of the status bar.

Show status bar example code:

// Show the status bar
LibWindowHelper.showStatusBar();
Enter fullscreen mode Exit fullscreen mode

Hide status bar example code:

// Hide the status bar
LibWindowHelper.hideStatusBar();
Enter fullscreen mode Exit fullscreen mode

Precautions

  • Ensure that the LibWindowHelper class is correctly imported and available in your project before calling its methods.
  • Carefully check the parameters passed in when calling the methods to ensure they are correct and in accordance with the documentation of LibWindowHelper.
  • If you encounter errors when calling the methods, carefully review the error messages output to the console and debug and fix them according to the error messages.
  • Full-screen display mode may affect the layout and user experience of the app, so use it with caution.
  • Modifying the style and color of the status bar may affect the overall visual effect of the app. It is recommended to maintain consistency with the app theme when designing.

IX. Conclusion

As a practical tool in HarmonyOS app development, the Page Management Utility Class provides developers with powerful capabilities for page layout and display management. By mastering the core attributes and methods of this utility class, developers can easily tackle various page management challenges and offer users a higher quality, more personalized interface experience. I hope this article helps you better understand and use the Page Management Utility Class, adding more power to your HarmonyOS app development journey.

Top comments (0)