HarmonyOS NEXT实战:沉浸式效果工具

简介: 本课程讲解如何在HarmonyOS中封装工具类,实现沉浸式布局效果。重点解析状态栏与导航条避让处理及UI适配策略,并通过TypeScript代码演示全屏、隐藏系统栏及避让区监听等核心功能的实现。

HarmonyOS Next实战##HarmonyOS SDK应用服务##教育

目标:封装工具类,实现沉浸式效果。

典型应用全屏窗口UI元素包括状态栏、应用界面和底部导航条,其中状态栏和导航条,通常在沉浸式布局下称为避让区;避让区之外的区域称为安全区。开发应用沉浸式效果主要指通过调整状态栏、应用界面和导航条的显示效果来减少状态栏导航条等系统界面的突兀感,从而使用户获得最佳的UI体验。

开发应用沉浸式效果主要要考虑如下几个设计要素:

  • UI元素避让处理:导航条底部区域可以响应点击事件,除此之外的可交互UI元素和应用关键信息不建议放到导航条区域。状态栏显示系统信息,如果与界面元素有冲突,需要考虑避让状态栏。
  • 沉浸式效果处理:将状态栏和导航条颜色与界面元素颜色相匹配,不出现明显的突兀感。

实战:

import {
    Rect } from '@ohos.application.AccessibilityExtensionAbility';
import {
    window } from '@kit.ArkUI';
import {
    BusinessError } from '@kit.BasicServicesKit';
import {
    UIAbility } from '@kit.AbilityKit';
import {
    KeyboardAvoidMode } from '@kit.ArkUI';

export namespace StageModelKit {
   
  export class StageModel {
   
    static UIAbility: Map<string, UIAbility> = new Map<string, UIAbility>();
    static UIAbilityContext: Map<string, Context> = new Map<string, Context>();
    static WindowStage: Map<string, window.WindowStage> = new Map<string, window.WindowStage>();

    /**
     * 登记
     * @param UIAbilityContext
     * @param WindowStage
     */
    static register(UIAbilityContext: Map<string, Context>, WindowStage: Map<string, window.WindowStage>) {
   
      UIAbilityContext.forEach((value: Context, key: string, map: Map<string, Context>) => {
   
        StageModel.UIAbilityContext.set(key, value)
      })

      WindowStage.forEach((value: window.WindowStage, key: string, map: Map<string, window.WindowStage>) => {
   
        StageModel.WindowStage.set(key, value)
      })
    }
  }

  export class Window {
   
    private windowStageName: string;
    windowStage: window.WindowStage;
    avoidArea: AvoidArea;
    keyboardHeight: number;

    constructor(windowStageName: string) {
   
      this.windowStageName = windowStageName
      this.windowStage = new Object() as window.WindowStage
      const zeroRect: Rect = {
   
        left: 0,
        top: 0,
        width: 0,
        height: 0
      }
      this.avoidArea = new AvoidArea(zeroRect, zeroRect)
      this.keyboardHeight = 0
    }

    init() {
   
      //初始化 windowStage
      const windowStage = StageModel.WindowStage.get(this.windowStageName)
      if (windowStage) {
   
        this.windowStage = windowStage
      } else {
   
        throw new Error(`[异常][未获取到windowStage,请检查StageModel和windowStageName是否正确引用] windowStage is ${
     JSON.stringify(windowStage)}`)
      }
      //初始化 avoidArea
      const getWindow = this.windowStage.getMainWindowSync(); // 获取应用主窗口
      const topRect = getWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM).topRect // 系统状态栏顶部区域
      const bottomRect =
        getWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR).bottomRect // 导航条底部区域
      this.avoidArea = new AvoidArea(rect_px2vp(topRect), rect_px2vp(bottomRect))
    }

    /**
     * 沉浸式效果
     */
    setImmersiveEffect() {
   
      this.watchAvoidArea()
      this.watchKeyboardHeight()
      this.setFullScreen()
      // 设置虚拟键盘抬起时压缩页面大小为减去键盘的高度
      this.windowStage.getMainWindowSync().getUIContext().setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE);
    }

    /**
     * 监控避让区
     */
    watchAvoidArea() {
   
      this.windowStage.getMainWindowSync().on('avoidAreaChange', (data) => {
   
        if (data.type === window.AvoidAreaType.TYPE_SYSTEM) {
   
          let avoidArea = this.avoidArea as AvoidArea
          avoidArea.topRect = rect_px2vp(data.area.topRect)
          this.avoidArea = avoidArea
        } else if (data.type == window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
   
          let avoidArea = this.avoidArea as AvoidArea
          avoidArea.bottomRect = rect_px2vp(data.area.bottomRect)
          this.avoidArea = avoidArea
        }else if (data.type == window.AvoidAreaType.TYPE_KEYBOARD) {
   
          // this.keyboardHeight = px2vp(data.area.bottomRect.height) //键盘高度
          // DeepalLogUtils.debug(`[日志]watchAvoidArea, keyboardHeight=${JSON.stringify(this.keyboardHeight)}`);
        }
      });
    }

    /**
     * 监控软键盘高度
     */
    watchKeyboardHeight() {
   
      this.windowStage.getMainWindowSync().on('keyboardHeightChange', (data: number) => {
   
        this.keyboardHeight = px2vp(data);
      });
    }

    /**
     * 设置全屏
     */
    setFullScreen() {
   
      this.windowStage.getMainWindowSync()
        .setWindowLayoutFullScreen(true)
        .then(() => {
   
          console.info('Succeeded in setting the window layout to full-screen mode.');
        })
        .catch((err: BusinessError) => {
   
          console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err));
        });
    }

    /**
     * 取消全屏
     */
    cancelFullScreen() {
   
      this.windowStage.getMainWindowSync()
        .setWindowLayoutFullScreen(false)
        .then(() => {
   
          console.info('Succeeded in setting the window layout to full-screen mode.');
        })
        .catch((err: BusinessError) => {
   
          console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err));
        });
    }

    /**
     * 隐藏头部状态栏
     */
    hideSystemTopStatusBar() {
   
      this.windowStage.getMainWindowSync()
        .setSpecificSystemBarEnabled('status', false)
        .then(() => {
   
          console.info('Succeeded in setting the status bar to be invisible.');
        })
        .catch((err: BusinessError) => {
   
          console.error(`Failed to set the status bar to be invisible. Code is ${
     err.code}, message is ${
     err.message}`);
        });
    }

    /**
     * 显示头部状态栏
     */
    showSystemTopStatusBar() {
   
      this.windowStage.getMainWindowSync()
        .setSpecificSystemBarEnabled('status', true)
        .then(() => {
   
          console.info('Succeeded in setting the status bar to be invisible.');
        })
        .catch((err: BusinessError) => {
   
          console.error(`Failed to set the status bar to be invisible. Code is ${
     err.code}, message is ${
     err.message}`);
        });
    }

    /**
     * 隐藏底部导航条
     */
    hideSystemBottomNavigationBar() {
   
      this.windowStage.getMainWindowSync()
        .setSpecificSystemBarEnabled('navigationIndicator', false)
        .then(() => {
   
          console.info('Succeeded in setting the navigation indicator to be invisible.');
        })
        .catch((err: BusinessError) => {
   
          console.error(`Failed to set the navigation indicator to be invisible. Code is ${
     err.code}, message is ${
     err.message}`);
        });
    }

    /**
     * 显示底部区域
     */
    showSystemBottomNavigationBar() {
   
      this.windowStage.getMainWindowSync()
        .setSpecificSystemBarEnabled('navigationIndicator', true)
        .then(() => {
   
          console.info('Succeeded in setting the navigation indicator to be invisible.');
        })
        .catch((err: BusinessError) => {
   
          console.error(`Failed to set the navigation indicator to be invisible. Code is ${
     err.code}, message is ${
     err.message}`);
        });
    }
  }

  /**
   * 避让区
   */
  class AvoidArea {
   
    topRect: Rect;
    bottomRect: Rect;

    constructor(topRect: Rect, bottomRect: Rect) {
   
      this.topRect = topRect
      this.bottomRect = bottomRect
    }
  }

  /**
   * 将矩形的px单位的数值转换为以vp为单位的数值
   * @param rect
   * @returns
   */
  function rect_px2vp(rect: Rect): Rect {
   
    return {
   
      left: px2vp(rect.left),
      top: px2vp(rect.top),
      width: px2vp(rect.width),
      height: px2vp(rect.height)
    } as Rect
  }
}
目录
相关文章
|
2月前
|
监控 JavaScript 编译器
从“天书”到源码:HarmonyOS NEXT 崩溃堆栈解析实战指南
本文详解如何利用 hiAppEvent 监控并获取 sourcemap、debug so 等核心产物,剖析了 hstack 工具如何将混淆的 Native 与 ArkTS 堆栈还原为源码,助力开发者掌握异常分析方法,提升应用稳定性。
423 40
|
3月前
|
开发者 容器
鸿蒙应用开发从入门到实战(十四):ArkUI组件Column&Row&线性布局
ArkUI提供了丰富的系统组件,用于制作鸿蒙原生应用APP的UI,本文主要讲解Column和Row组件的使用以及线性布局的方法。
306 12
|
3月前
|
API 数据处理
鸿蒙应用开发从入门到实战(十三):ArkUI组件Slider&Progress
ArkUI提供了丰富的系统组件,用于制作鸿蒙原生应用APP的UI,本文主要讲解滑块Slider和进度条Progress组件的使用。
189 1
|
3月前
|
JavaScript 开发者 索引
鸿蒙应用开发从入门到实战(九):ArkTS渲染控制
ArkTS拓展了TypeScript,可以结合ArkUI进行渲染控制,是的界面设计具有可编程性。本文简要描述鸿蒙应用开发中的条件渲染和循环渲染。
181 5
|
2月前
|
移动开发 前端开发 Android开发
【02】建立各项目录和页面标准化产品-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【02】建立各项目录和页面标准化产品-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
298 12
【02】建立各项目录和页面标准化产品-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
|
2月前
|
移动开发 JavaScript 应用服务中间件
【06】优化完善落地页样式内容-精度优化-vue加vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【06】优化完善落地页样式内容-精度优化-vue加vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
259 5
【06】优化完善落地页样式内容-精度优化-vue加vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
|
2月前
|
移动开发 Rust JavaScript
【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
612 4
【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
|
3月前
|
数据安全/隐私保护 开发者
鸿蒙应用开发从入门到实战(十一):ArkUI组件Text&TextInput
ArkUI提供了丰富的系统组件,用于制作鸿蒙原生应用APP的UI,本文主要讲解文本组件Text和TextInput的使用。
296 3
|
2月前
|
移动开发 Android开发
【03】建立隐私关于等相关页面和内容-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【03】建立隐私关于等相关页面和内容-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
157 0
|
3月前
|
存储 缓存 5G
鸿蒙 HarmonyOS NEXT端云一体化开发-云存储篇
本文介绍用户登录后获取昵称、头像的方法,包括通过云端API和AppStorage两种方式,并实现上传头像至云存储及更新用户信息。同时解决图片缓存问题,添加上传进度提示,支持自动登录判断,提升用户体验。
182 1

热门文章

最新文章