鸿蒙 HarmonyOS(ArkTS) 沉浸式工具封装

16 阅读1分钟

鸿蒙 HarmonyOS(ArkTS)中沉浸式工具封装

小知识:


1.共享context 对象

PixPin_2025-06-02_21-28-08.png

PixPin_2025-06-02_21-29-47.png

//共享context对象
AppStorage.setOrCreate('CONTEXT', this.context)

2.封装(commons/utils/FullScreen.ets)

import { window } from '@kit.ArkUI'
import { logger } from '.'
import { BOTTOM_HEIGHT, TOP_HEIGHT } from '../constants'

class FullScreen {
  //开启沉浸式工具
  async enable() {
    try {
      //获取context对象
      const ctx = AppStorage.get<Context>('context')
      if (ctx) {
        //获取窗口对象
        const win = await window.getLastWindow(ctx)
        //开启全屏(开启沉浸式)
        await win.setWindowLayoutFullScreen(true)
        //获取状态栏高度
        const topHeight = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM)
        //存储高度
        AppStorage.setOrCreate('TOP_HEIGHT', px2vp(topHeight.topRect.height))
        //获取导航栏高度
        const bottomHeight = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR)
        //存储高度
        AppStorage.setOrCreate('BOTTOM_HEIGHT', px2vp(bottomHeight.bottomRect.height))
      }
    } catch (err) {
      //捕获错误
      logger.error('fullScreen', err)
    }
  }

  //关闭沉浸式
  async disable() {
    try {
      //获取context对象
      const ctx = AppStorage.get<Context>('context')
      if (ctx) {
        //获取窗口对象
        const win = await window.getLastWindow(ctx)
        //关闭沉浸式
        await win.setWindowLayoutFullScreen(false)
        //设置状态栏和导航条高度
        AppStorage.setOrCreate(TOP_HEIGHT, 0)
        AppStorage.setOrCreate(BOTTOM_HEIGHT, 0)
      }
    } catch (err) {
      logger.error('fullScreen', err)
    }
  }
}

export const fullscreen = new FullScreen()

3.统一向外导出

创建一个index用于统一导出封装的工具

PixPin_2025-06-02_21-32-10.png

PixPin_2025-06-02_21-32-20.png

4.导出常量 定义一个常量名用于后续使用

PixPin_2025-06-02_21-34-57.png