HarmonyOS NEXT - 沉浸式工具

一.沉浸式窗口安全区域

💡 Tips:方法一:调用主窗口

AvoidAreaType

这个接口适用两种场景:

1》在onWindowStageCreate 中,获取应用启动时的初始布局避让区域时可调用接口

2》当应用内子窗口需要临时显示,对显示内容做布局避让时可调用该窗口。

  • devicInfo 提供终端设备信息
  • window窗口

    设置在应用的主页面的entryability

    //entryability /onWindowStageCreate
    
    //设置全屏
    const win = windowStage.getMainWindowSync()
    win.setWindowLayoutFullScreen(true)
    
    //在应用中存储顶部安全高度
    const top = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM).topRect
    AppStorage.setOrCreate<number>(SafeAreaConstants.safeTop, px2vp(top.height))
    //在应用中存储底部安全高度
    const bottom = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR).bottomRect
    AppStorage.setOrCreate<number>(SafeAreaConstants.safeBottom, px2vp(bottom.height))

    主要用到的API

    1.窗口

    windowStage 窗口管理器,管理各个基本窗口单元。

    属性:getMainWindow获取这个对象下的主窗口,异步回调函数。

  • 在主窗口下引用属性setWindowLayoutFullScreen 主窗口或者子窗口是否为沉浸式布局,使用promise异步回调。参数类型是布尔型 true表示沉浸式布局,false表示非沉浸式布局。
  • getWindowAvoidArea 当前窗口要规避的区域

封装方法 

通用工具代码/ FullScreen

import { window } from '@kit.ArkUI'

// context 是应用上下文,应用提供的一些功能对象
// 1. 组件中 getContext(this) 获取, this 组件实例, 如果是在非组件调用获取的是 undefined
// 2. 在 Ability 中,this.context 可以获取上下文

class FullScreen {
  // 开启全屏
  async enable () {
    const ctx = AppStorage.get<Context>('context')
    if (ctx) {
      const win = await window.getLastWindow(ctx)
      // true 开启沉浸式
      win.setWindowLayoutFullScreen(true)
    }
  }
  // 关闭全屏
  async disable () {
    const ctx = AppStorage.get<Context>('context')
    if (ctx) {
      const win = await window.getLastWindow(ctx)
      // false 关闭沉浸式
      win.setWindowLayoutFullScreen(false)
    }
  }
}

export const fullScreen = new FullScreen()

注意:获取上下文应用

1.在组件内获取上下文应用

直接

const ctx = getContext(this)

2.非组件内获取上下文应用

const ctx = AppStorage.get<Context>('context') 

import { fullScreen } from '../commons/utils/FullScreen';
//应用程序主入口中
export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    logger.info('Ability onCreate');
    // 共享给应用所有位置使用context
    AppStorage.setOrCreate('context', this.context)
  }

onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    logger.info('Ability onWindowStageCreate');
    //开启沉浸式
    fullScreen.enable()
    windowStage.loadContent('pages/Index', (err) => {
      if (err.code) {
        logger.error('Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      logger.info('Succeeded in loading the content.');
    });
  }

 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值