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
  }
}
目录
相关文章
|
4月前
|
容器
HarmonyOS NEXT仓颉开发语言实战案例:外卖App
仓颉语言实战分享,教你如何用仓颉开发外卖App界面。内容包括页面布局、导航栏自定义、搜索框实现、列表模块构建等,附完整代码示例。轻松掌握Scroll、List等组件使用技巧,提升HarmonyOS应用开发能力。
|
3月前
|
移动开发 前端开发 JavaScript
鸿蒙NEXT时代你所不知道的全平台跨端框架:CMP、Kuikly、Lynx、uni-app x等
本篇基于当前各大活跃的跨端框架的现状,对比当前它们的情况和未来的可能,帮助你在选择框架时更好理解它们的特点和差异。
312 0
|
4月前
|
安全 API 开发工具
【HarmonyOS NEXT】一键扫码功能
这些Kit为我们应用开发提升了极大地效率。很多简单的功能,如果不需要太深的定制化需求,直接调用kit提供的API就可以实现,在android或者ios上需要很多代码才能实现的功能效果。
119 0
HarmonyOS NEXT仓颉开发语言实战案例:电影App
周末好!本文分享使用仓颉语言重构ArkTS实现的电影App案例,对比两者在UI布局、组件写法及语法差异。内容包括页面结构、列表分组、分类切换与电影展示等。通过代码演示仓颉在HarmonyOS开发中的应用。##仓颉##ArkTS##HarmonyOS开发
|
4月前
|
容器
HarmonyOS NEXT仓颉开发语言实战案例:健身App
本期分享一个健身App首页的布局实现,顶部采用Stack容器实现重叠背景与偏移效果,列表部分使用List结合Scroll实现可滚动内容。代码结构清晰,适合学习HarmonyOS布局技巧。
HarmonyOS NEXT仓颉开发语言实战案例:小而美的旅行App
本文分享了一个旅行App首页的设计与实现,使用List容器搭配Row、Column布局完成个人信息、功能列表及推荐模块的排版,详细展示了HarmonyOS下的界面构建技巧。
|
18天前
|
存储 缓存 5G
鸿蒙 HarmonyOS NEXT端云一体化开发-云存储篇
本文介绍用户登录后获取昵称、头像的方法,包括通过云端API和AppStorage两种方式,并实现上传头像至云存储及更新用户信息。同时解决图片缓存问题,添加上传进度提示,支持自动登录判断,提升用户体验。
90 0
|
18天前
|
存储 负载均衡 数据库
鸿蒙 HarmonyOS NEXT端云一体化开发-云函数篇
本文介绍基于华为AGC的端云一体化开发流程,涵盖项目创建、云函数开通、应用配置及DevEco集成。重点讲解云函数的编写、部署、调用与传参,并涉及环境变量设置、负载均衡、重试机制与熔断策略等高阶特性,助力开发者高效构建稳定云端服务。
178 0
鸿蒙 HarmonyOS NEXT端云一体化开发-云函数篇
|
18天前
|
存储 JSON 数据建模
鸿蒙 HarmonyOS NEXT端云一体化开发-云数据库篇
云数据库采用存储区、对象类型、对象三级结构,支持灵活的数据建模与权限管理,可通过AGC平台或本地项目初始化,实现数据的增删改查及端侧高效调用。
50 0
|
18天前
|
存储 开发者 容器
鸿蒙 HarmonyOS NEXT星河版APP应用开发-ArkTS面向对象及组件化UI开发使用实例
本文介绍了ArkTS语言中的Class类、泛型、接口、模块化、自定义组件及状态管理等核心概念,并结合代码示例讲解了对象属性、构造方法、继承、静态成员、访问修饰符等内容,同时涵盖了路由管理、生命周期和Stage模型等应用开发关键知识点。
150 0
鸿蒙 HarmonyOS NEXT星河版APP应用开发-ArkTS面向对象及组件化UI开发使用实例