DEV Community

HarmonyOS
HarmonyOS

Posted on

How To Dynamically Control The Page Display Size To Follow System Changes

Read the original article:How To Dynamically Control The Page Display Size To Follow System Changes

How To Dynamically Control The Page Display Size To Follow System Changes

Problem Description

How to dynamically control the page display size to follow system changes, that is, when the system settings screen resolution changes, the page is opened and does not follow the system changes. The page is not opened and follows the system changes the next time it is opened.

Background Knowledge

The setDefaultDensityEnabled method provided in Interface (WindowStage) is used to set whether the application display size scales with system changes. If this method is not called to set the setting, the system default density is not used, that is, the application display size will not automatically adjust with system changes.

AppStorage: It is the core tool for global state management of HarmonyOS applications. It achieves flexible synchronization with UI components through decorators and is suitable for shared state scenarios across components and UIAbilities.

Solution

The WindowStage object is stored globally in EntryAbility so that it can be shared throughout the application. In the page that needs to be set, the state is managed through the page lifecycle method, and the system resolution is set not to follow the system changes when the page is displayed. The specific implementation is as follows:

1.In the onWindowStageCreate method in EntryAbility, use AppStorage to globally store the WindowStage object to achieve application-level global state sharing.

import { UIAbility } from '@kit.AbilityKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage) {
    // ...
   AppStorage.setOrCreate('windowStage', windowStage)
  }
};
Enter fullscreen mode Exit fullscreen mode

2.Next, in the page that needs to be configured, use onPageHide and onPageShow to listen for the page's display and hiding events, thereby setting setDefaultDensityEnabled to true, which will prevent the system resolution from changing with the system.

import { window } from '@kit.ArkUI'

@Entry
@Component
struct Page9 {
  @State isShow: boolean = false

  onPageShow(): void {
    if (this.isShow) {
      (AppStorage.get('windowStage') as window.WindowStage).setDefaultDensityEnabled(true)
    }
  }

  onPageHide(): void {
    this.isShow = true
  }

  build() {
    Column() {
      Text(this.isShow ? "Do not follow system resolution changes" : "Follow system\nresolution changes").margin({top:60})
    }
    .height('100%')
    .width('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

Code running effect diagram:

cke_1712.png

Code Clear Screenshot

cke_3385.png

Written by Recep Sadullah Yegin

Top comments (0)