【鸿蒙应用ArkTS开发系列】- 沉浸式状态栏实现
创始人
2024-11-10 04:10:15
0

文章目录

  • 一、前言
  • 二、封装沉浸式状态栏管理类
    • 1、创建Demo工程
    • 2、封装状态栏管理类
  • 三、编写页面实现沉浸式状态栏效果
    • 1、存储windowStage实例
    • 2、Page页面中实现沉浸式开启关闭功能
      • 2.1、开启沉浸式状态栏
      • 2.2、设置标题栏偏移量

一、前言

在应用开发中,页面跟状态栏的默认显示效果一般是如下:
在这里插入图片描述
但是产品UI设计的时候,一般是会设计一个沉浸式状态的页面效果,如下:
在这里插入图片描述
那在鸿蒙应用开发中,应该怎么实现这个沉浸式状态栏的效果呢?下面我们来创建一个Demo工程进行讲解。

二、封装沉浸式状态栏管理类

1、创建Demo工程

首先我们创建一个Demo工程,在ets目录下创建common文件夹。
在这里插入图片描述

2、封装状态栏管理类

我们在common目录中创建StatusBarManager.ts文件,完整的代码如下:

import window from '@ohos.window'; import HashMap from '@ohos.util.HashMap'; import { Log } from './Log';  /**  * 状态栏管理器  */ export class StatusBarManager {   private readonly TAG = 'StatusBarManager';   private readonly CONFIG_SYSTEM_BAR_HEIGHT = 'systemBarHeight';   private static mInstance: StatusBarManager;   private mWindowStage: window.WindowStage;    private mConfig = new HashMap();    private constructor() {   }    public static get(): StatusBarManager {     if (!this.mInstance) {       this.mInstance = new StatusBarManager();     }     return this.mInstance;   }    /**    * 存储windowStage实例    * @param windowStage    */   public storeWindowStage(windowStage: window.WindowStage) {     this.mWindowStage = windowStage;   }    /**    * 获取windowStage实例    * @returns    */   public getWindowStage(): window.WindowStage {     return this.mWindowStage;   }    /**    * 设置沉浸式状态栏    * @param windowStage    * @returns    */   public setImmersiveStatusBar(windowStage: window.WindowStage): Promise {      let resolveFn, rejectFn;     let promise = new Promise((resolve, reject) => {       resolveFn = resolve;       rejectFn = reject;     });      // 1.获取应用主窗口。     try {       let windowClass = windowStage.getMainWindowSync();       Log.info(this.TAG, 'Succeeded in obtaining the main window. Data: ' + JSON.stringify(windowClass));        // 2.实现沉浸式效果:设置窗口可以全屏绘制。       // 将UI内容顶入状态栏下方       windowClass.setWindowLayoutFullScreen(true)         .then(() => {           //3、设置状态栏 可见           windowClass.setWindowSystemBarEnable(['status']).then(() => {             //4、设置状态栏透明背景             const systemBarProperties: window.SystemBarProperties = {               statusBarColor: '#00000000'             };             //设置窗口内导航栏、状态栏的属性             windowClass.setWindowSystemBarProperties(systemBarProperties)               .then(() => {                 Log.info(this.TAG, 'Succeeded in setting the system bar properties.');               }).catch((err) => {               Log.error(this.TAG, 'Failed to set the system bar properties. Cause: ' + JSON.stringify(err));             });           })            //5、存储状态栏高度           this.storeStatusBarHeight(windowClass);            resolveFn();         });      } catch (err) {       Log.error(this.TAG, 'Failed to obtain the main window. Cause: ' + JSON.stringify(err));       rejectFn();     }      return promise;    }    /**    * 关闭沉浸式状态栏    * @param windowStage    * @returns    */   public hideImmersiveStatusBar(windowStage: window.WindowStage): Promise {      let resolveFn, rejectFn;     let promise = new Promise((resolve, reject) => {       resolveFn = resolve;       rejectFn = reject;     });     // 1.获取应用主窗口。     try {       let windowClass = windowStage.getMainWindowSync();       Log.info(this.TAG, 'Succeeded in obtaining the main window. Data: ' + JSON.stringify(windowClass));        windowClass.setWindowLayoutFullScreen(false)         .then(() => {           //存储状态栏高度           this.mConfig.set(this.CONFIG_SYSTEM_BAR_HEIGHT, 0);           resolveFn();         });      } catch (err) {       Log.error(this.TAG, 'Failed to obtain the main window. Cause: ' + JSON.stringify(err));       rejectFn(err);     }     return promise;    }     /**    * 获取状态栏高度进行保存    * @param windowClass    * @returns    */   private storeStatusBarHeight(windowClass: window.Window) {      try {       const avoidArea = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);       // 保存高度信息       this.mConfig.set(this.CONFIG_SYSTEM_BAR_HEIGHT, avoidArea.topRect.height);       Log.info(this.TAG, 'Succeeded in obtaining the area. Data:' + JSON.stringify(avoidArea));      } catch (err) {       Log.error(this.TAG, 'Failed to obtain the area. Cause:' + JSON.stringify(err));     }   }    /**    * 未开启沉浸式状态栏,偏移量为0,开启, 偏移量为状态栏高度    * @returns    */   public getSystemBarOffset(): number {     let height = 0;     if (this.mConfig.hasKey(this.CONFIG_SYSTEM_BAR_HEIGHT)) {       height = this.mConfig.get(this.CONFIG_SYSTEM_BAR_HEIGHT) as number;     }     return height;   }    /**    * 是否开启沉浸式状态栏    * @returns    */   public isOpenImmersiveStatusBar(): boolean {     return this.getSystemBarOffset() > 0;   } }  

StatusBarManager 管理类主要提供以下常用的方法:

  • get- 获取管理类单例实例
  • storeWindowStage- 存储windowStage实例
    该方法在UIAbility中进行调用。
  • getWindowStage- 获取windowStage实例
  • setImmersiveStatusBar- 设置沉浸式状态栏
  • hideImmersiveStatusBar- 关闭沉浸式状态栏
  • storeStatusBarHeight- (内部私有方法)获取状态栏高度进行保存
  • getSystemBarOffset- 获取状态栏高度(沉浸式状态栏下需要调整的标题偏移量)
  • isOpenImmersiveStatusBar- 是否开启沉浸式状态栏

下面我们主要讲解下setImmersiveStatusBar方法,设置沉浸式状态栏,这个过程主要分为五个步骤:

1、获取应用主窗口

let windowClass = windowStage.getMainWindowSync(); 

我们通过传入的windowStage,同步获取一个主窗口实例。

2、设置窗口可以全屏绘制

windowClass.setWindowLayoutFullScreen(true) 

我们将窗口设置为全屏模式。

3、设置状态栏可见

windowClass.setWindowSystemBarEnable(['status']) 

在设置全屏后,状态栏不可见,我们需要的不是全屏效果,而是状态栏沉浸式效果,因此需要将状态栏设置为可见。
这里入参是一个数组,可以设置状态栏、也可以设置底部导航栏。

4、设置窗口内状态栏背景为透明

const systemBarProperties: window.SystemBarProperties = {               statusBarColor: '#00000000' }; windowClass.setWindowSystemBarProperties(systemBarProperties)               .then(() => {                 Log.info(this.TAG, 'Succeeded in setting the system bar properties.');               }).catch((err) => {               Log.error(this.TAG, 'Failed to set the system bar properties. Cause: ' + JSON.stringify(err));             }); 

状态栏设置为显示状态后,我们给状态栏的背景色设置为透明,这里才能达到沉浸式的效果。

5、存储状态栏高度

const avoidArea = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM); // 保存高度信息 this.mConfig.set(this.CONFIG_SYSTEM_BAR_HEIGHT, avoidArea.topRect.height); 

我们通过上述代码可以获取系统状态栏的高度,并将其保存起来,后续页面通过该高度来判断是否是开启了沉浸式状态栏。

这样我们的状态栏管理类就封装完毕,下面我们来写下页面UI实现沉浸式页面状态栏效果。

三、编写页面实现沉浸式状态栏效果

1、存储windowStage实例

具体如下:

  onWindowStageCreate(windowStage: window.WindowStage): void {     // Main window is created, set main page for this ability     hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');      StatusBarManager.get().storeWindowStage(windowStage);      windowStage.loadContent('pages/Index', (err, data) => {       if (err.code) {         hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');         return;       }       hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');     });   } 

在EntryAbility.ts 文件 onWindowStageCreate方法中添加如下代码:

StatusBarManager.get().storeWindowStage(windowStage); 

我们这个Demo效果,是在单个Page中开启关闭沉浸式效果,因此我们需要在UIAbility中存储windowStage实例。

实际应用使用中,如果需要所有Page都开启沉浸式状态效果,则可以将上述代码调整为

StatusBarManager.get().setImmersiveStatusBar(windowStage); 

2、Page页面中实现沉浸式开启关闭功能

2.1、开启沉浸式状态栏

我们拷贝如下代码到Index.ets 文件中:

import { StatusBarManager } from '../common/StatusBarManager';  @Entry @Component struct Index {   @State showImmersiveStatusBar: boolean = false;    build() {     Column() {        Column() {         Column() {           Text('这是标题')             .fontSize(20)             .fontColor(Color.White)         }         .height(50)         .justifyContent(FlexAlign.Center)       }       .width('100%')       .backgroundColor('#ff007dfe')        Column() {         Text('点击开启沉浸式状态栏')           .fontSize(16)          Button(this.showImmersiveStatusBar ? '关闭' : '开启')           .fontSize(16)           .margin({ top: 20 })           .padding({ left: 50, right: 50 })           .onClick(() => {              if (this.showImmersiveStatusBar) {               this.close();             } else {               this.open();             }             this.showImmersiveStatusBar = !this.showImmersiveStatusBar;           })       }       .width('100%')       .height('100%')       .justifyContent(FlexAlign.Center)     }     .height('100%')   }    private open() {     let windowStage = StatusBarManager.get().getWindowStage();     if (windowStage) {       StatusBarManager.get().setImmersiveStatusBar(windowStage);     }   }    private close() {     let windowStage = StatusBarManager.get().getWindowStage();     if (windowStage) {       StatusBarManager.get().hideImmersiveStatusBar(windowStage);     }   } } 

我们运行下代码将应用装到手机上看看效果**
(真机配置签名方式前面文章有示例讲解,不懂的同学可以翻下我之前的文章看下)**
具体效果如下:
在这里插入图片描述
我们点击下开启看下效果,
在这里插入图片描述
咋看以下好像没什么问题,但是如果手机是居中挖孔屏,那我们的标题就会显示在摄像头位置上,影响页面布局的正常显示,那这个问题应该怎么处理呢。
大家还记得我们上面封装状态栏管理器的时候,对外提供了一个获取状态栏高度偏移量的方法吗,这个时候我们就需要用到它了。

2.2、设置标题栏偏移量

在这里插入图片描述

我们在布局中,对标题栏设置一个上方的Padding,数值为状态栏高度即可,那这个偏移量怎么获取呢,在什么时候获取呢?我们接着往下看。

 private open() {     let windowStage = StatusBarManager.get().getWindowStage();     if (windowStage) {       StatusBarManager.get().setImmersiveStatusBar(windowStage)         .then(() => {           this.titleBarPadding= StatusBarManager.get().getSystemBarOffset();         });     }   } 

我们封装setImmersiveStatusBar的时候,是在执行沉浸式状态栏完成后,使用Promise方式返回了结果,表明沉浸式状态栏开启完成,我们只需要使用then关键字,在代码块中调用 getSystemBarOffset获取高度后设置给titleBarPadding即可。
下面贴下修改后的完整代码:

import { StatusBarManager } from '../common/StatusBarManager';  @Entry @Component struct Index {   @State showImmersiveStatusBar: boolean = false;   @State titleBarPadding: number = 0;    build() {     Column() {        Column() {         Column() {           Text('这是标题')             .fontSize(20)             .fontColor(Color.White)         }         .height(50)         .justifyContent(FlexAlign.Center)       }       .padding({ top: `${this.titleBarPadding}px` })       .width('100%')       .backgroundColor('#ff007dfe')        Column() {         Text('点击开启沉浸式状态栏')           .fontSize(16)          Button(this.showImmersiveStatusBar ? '关闭' : '开启')           .fontSize(16)           .margin({ top: 20 })           .padding({ left: 50, right: 50 })           .onClick(() => {              if (this.showImmersiveStatusBar) {               this.close();             } else {               this.open();             }             this.showImmersiveStatusBar = !this.showImmersiveStatusBar;           })       }       .width('100%')       .height('100%')       .justifyContent(FlexAlign.Center)     }     .height('100%')   }    private open() {     let windowStage = StatusBarManager.get().getWindowStage();     if (windowStage) {       StatusBarManager.get().setImmersiveStatusBar(windowStage)         .then(() => {           this.titleBarPadding = StatusBarManager.get().getSystemBarOffset();         });     }   }    private close() {     let windowStage = StatusBarManager.get().getWindowStage();     if (windowStage) {       StatusBarManager.get().hideImmersiveStatusBar(windowStage).then(() => {         this.titleBarPadding = 0;       })     }   } } 

下面我们重新运行看下效果:
在这里插入图片描述
看起来效果还可以,开启沉浸式状态栏后,页面的UI展示效果明显提到了一个档次哈哈。

本文到此完毕,如果有什么疑问,欢迎评论区沟通探讨。谢谢大家的阅读!

相关内容

热门资讯

秒懂普及”珊瑚互娱房卡领取码“... 秒懂普及”珊瑚互娱房卡领取码“王者大厅房间卡怎么购买游戏中心打开微信,添加客服【113857776】...
秒懂教程!我买微信牛牛房卡链接... 斗牛是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:71319951许多玩家在游戏中会购买房卡来享受...
正规平台有哪些,怎么买斗牛房卡... 微信游戏中心:火神大厅房卡在哪里买打开微信,添加客服微信【88355042】,进入游戏中心或相关小程...
给大家讲解“购买斗牛房卡联系方... 起点大厅是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:160470940许多玩家在游戏中会购买房卡...
ia攻略/游戏推荐斗牛房卡出售... ia攻略/游戏推荐斗牛房卡出售长虹大厅/科技房卡多少钱一张Sa9Ix苹果iPhone 17手机即将进...
一分钟实测分享”时光互娱低价获... 第二也可以在游戏内商城:在游戏界面中找到 “微信金花,斗牛链接房卡”“商城”选项,选择房卡的购买选项...
一分钟了解!牛牛房卡游戏平台加... 微信游戏中心:乐乐堂房卡在哪里买打开微信,添加客服微信【88355042】,进入游戏中心或相关小程序...
正规平台有哪些,金花房卡是正规... 海航大厅是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:【3329006910】或QQ:332900...
秒懂教程!微信牛牛房间怎么弄,... 斗牛是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:66336574许多玩家在游戏中会购买房卡来享受...
终于找到“微信怎样开炸金花房间... 金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:160470940许多玩家在游戏中会购买房卡来享...
秒懂百科”海洋世界哪里有详细房... 哪里有详细房卡介绍是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:113857776许多玩家在游戏中...
头条推荐!游戏推荐斗牛房卡出售... 头条推荐!游戏推荐斗牛房卡出售新神兽/流樱大厅/微信链接房间卡怎么购买新神兽/流樱大厅是一款非常受欢...
推荐一款!怎么买斗牛房卡朱雀大... 微信游戏中心:朱雀大厅房卡在哪里买打开微信,添加客服微信【88355042】,进入游戏中心或相关小程...
玩家攻略,牛牛房卡代理荣耀联盟... 荣耀联盟是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:【3329006910】或QQ:332900...
IA解析/牛牛房卡游戏平台加盟... IA解析/牛牛房卡游戏平台加盟天道联盟/随意玩/微信链接房卡卖家联系方式Sa9Ix苹果iPhone ...
分享经验”百万牛哪里买低价获取... 分享经验”百万牛哪里买低价获取“新老夫子房卡充值游戏中心打开微信,添加客服【113857776】,进...
一分钟了解!金花房卡出售大众互... 今 日消息,大众互娱房卡添加微信33549083 苹果今日发布了 iOS 16.1 正式版更新,简单...
秒懂教程!微信买链接拼三张房卡... 拼三张是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:56001354许多玩家在游戏中会购买房卡来享...
房卡必备教程“购买金花房卡联系... 新琉璃金花是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:44346008许多玩家在游戏中会购买房卡...
1分秒分析”茄子娱乐房卡详细充... 第二也可以在游戏内商城:在游戏界面中找到 “微信金花,斗牛链接房卡”“商城”选项,选择房卡的购买选项...