【HarmonyOS Next】原生沉浸式界面

news2024/10/28 0:13:41

背景

在实际项目中,为了软件使用整体色调看起来统一,一般顶部和底部的颜色需要铺满整个手机屏幕。因此,这篇帖子是介绍设置的方法,也是应用沉浸式效果。如下图:底部的绿色延伸到上面的状态栏和下面的导航栏

UI

在鸿蒙应用中,全屏UI元素分为状态栏、应用界面和导航栏。

一般实现应用沉浸式效果由两种方式:

  • 窗口全屏布局方案:调整布局系统为全屏布局,界面元素延伸到状态栏和导航条区域实现沉浸式效果。
  • 组件延伸方案:组件布局在应用界面区域,通过接口方法延伸到状态栏和导航栏。

窗口全屏布局方案

  1. 新建展示页面,并使用@StorageProp定义页面内容的顶部偏移和底部偏移属性
@Entry
@Component
struct Index {
  @StorageProp('bottomRectHeight')
  bottomRectHeight: number = 0;
  @StorageProp('topRectHeight')
  topRectHeight: number = 0;

  build() {
    Row() {
      Column() {
        Row() {
          Text('DEMO-ROW1').fontSize(40)
        }.backgroundColor(Color.Orange).padding(20)

        Row() {
          Text('DEMO-ROW2').fontSize(40)
        }.backgroundColor(Color.Orange).padding(20)

        Row() {
          Text('DEMO-ROW3').fontSize(40)
        }.backgroundColor(Color.Orange).padding(20)

        Row() {
          Text('DEMO-ROW4').fontSize(40)
        }.backgroundColor(Color.Orange).padding(20)

        Row() {
          Text('DEMO-ROW5').fontSize(40)
        }.backgroundColor(Color.Orange).padding(20)

        Row() {
          Text('DEMO-ROW6').fontSize(40)
        }.backgroundColor(Color.Orange).padding(20)
      }
      .width('100%')
      .height('100%')
      .alignItems(HorizontalAlign.Center)
      .justifyContent(FlexAlign.SpaceBetween)
      .backgroundColor('#008000')
      // top数值与状态栏区域高度保持一致;bottom数值与导航条区域高度保持一致
      .padding({ top: px2vp(this.topRectHeight), bottom: px2vp(this.bottomRectHeight) })
    }
  }
}
  1. 在EntryAbility的onWindowStageCreate方法中,调用window.Window.setWindowLayoutFullScreen方法设置窗口全屏。
let windowClass: window.Window = windowStage.getMainWindowSync();
let isLayoutFullScreen = true;
    windowClass.setWindowLayoutFullScreen(isLayoutFullScreen).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));
    });
  1. 为了避免构件被挡住,根据导航条和状态栏的高度,修改bottomRectHeight和topRectHeight的数值。
    //获取导航栏高度
    let bottomRectHeight = windowClass
      .getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR)
      .bottomRect
      .height;
    AppStorage.setOrCreate('bottomRectHeight', bottomRectHeight);
    // 获取状态栏区域高度
    let topRectHeight = windowClass
      .getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM)
      .topRect
      .height;
    AppStorage.setOrCreate('topRectHeight', topRectHeight);
  1. 再设置页面监听,动态修改bottomRectHeight和topRectHeight的数值。
windowClass.on('avoidAreaChange', (data) => {
      if (data.type === window.AvoidAreaType.TYPE_SYSTEM) {
        let topRectHeight = data.area.topRect.height;
        AppStorage.setOrCreate('topRectHeight', topRectHeight);
      } else if (data.type == window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
        let bottomRectHeight = data.area.bottomRect.height;
        AppStorage.setOrCreate('bottomRectHeight', bottomRectHeight);
      }
    });

EntryAbility完整代码

仅需要修改onWindowStageCreate方法

onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    windowStage.loadContent('pages/Index', (err) => {
      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.');
    });
    // 获取应用主窗口
    let windowClass: window.Window = windowStage.getMainWindowSync();
    // 设置窗口全屏
    let isLayoutFullScreen = true;
    windowClass.setWindowLayoutFullScreen(isLayoutFullScreen).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));
    });
    //获取导航栏高度
    let bottomRectHeight = windowClass
      .getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR)
      .bottomRect
      .height;
    AppStorage.setOrCreate('bottomRectHeight', bottomRectHeight);
    // 获取状态栏区域高度
    let topRectHeight = windowClass
      .getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM)
      .topRect
      .height;
    AppStorage.setOrCreate('topRectHeight', topRectHeight);

    // 注册监听函数,动态获取避让区域数据
    windowClass.on('avoidAreaChange', (data) => {
      if (data.type === window.AvoidAreaType.TYPE_SYSTEM) {
        let topRectHeight = data.area.topRect.height;
        AppStorage.setOrCreate('topRectHeight', topRectHeight);
      } else if (data.type == window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
        let bottomRectHeight = data.area.bottomRect.height;
        AppStorage.setOrCreate('bottomRectHeight', bottomRectHeight);
      }
    });

  }

组件延伸方案

使用expandSafeArea方法来实现。

expandSafeArea(types?: Array<SafeAreaType>, edges?: Array<SafeAreaEdge>): T;
  • types:配置扩展安全区域的类型。SafeAreaType枚举类型,SYSTEM是系统默认非安全区域,包括状态栏、导航栏;CUTOUT是设备的非安全区域,例如刘海屏或挖孔屏区域;KEYBOARD是软键盘区域,组件不避让键盘。
  • edges:扩展安全区域的方向。

代码

通过颜色对比,可以看出组件延伸效果。

  • column:背景颜色设置为橘色,从图片可以看出只能在安全区域内显示。
  • list:背景颜色设置为黄色,从图片可以看出已经延伸至导航条和状态栏了。
  • Text:背景颜色设置成红色,就可以看到整个组件的滑动过程.

@Entry
@Component
struct ExamplePage {
  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

  build() {
    Column() {
      List({ space: 20, initialIndex: 0 }) {
        ForEach(this.arr, (item: number) => {
          ListItem() {
            Text('' + item)
              .width('100%')
              .height(100)
              .fontSize(16)
              .textAlign(TextAlign.Center)
              .borderRadius(10)
              .backgroundColor(Color.Red)
          }

        }, (item: number) => item.toString())
      }
      .listDirection(Axis.Vertical) // 排列方向
      .scrollBar(BarState.Off)
      .friction(0.6)
      .divider({
        strokeWidth: 2,
        color: 0xFFFFFF,
        startMargin: 20,
        endMargin: 20
      }) // 每行之间的分界线
      .edgeEffect(EdgeEffect.Spring) // 边缘效果设置为Spring
      .width('90%')
      .backgroundColor(Color.Yellow)
      // List组件的视窗范围扩展至导航条。
      .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
    }
    .width('100%')
    .height('100%')
    .backgroundColor(Color.Orange)
  }
}

总结

如果不是全部界面都需要实现沉浸式布局时,可以通过组件延伸方案去实现部分组件的沉浸式布局。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2225037.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Android 判断手机放置的方向

#1024程序员节&#xff5c;征文# 文章目录 前言一、pandas是什么&#xff1f;二、使用步骤 1.引入库2.读入数据总结 需求 老板&#xff1a;我有个手持终端&#xff0c;不能让他倒了&#xff0c;当他倒或者倾斜的时候要发出报警&#xff1b; 程序猿&#xff1a;我这..... 老板…

断点续传技术是什么?大型文件传输的新模式!

随着科技的不断进步&#xff0c;文件传输已成为我们日常生活和工作中不可或缺的一部分。然而&#xff0c;传输大型文件时常常会遇到网络不稳定、传输中断等问题&#xff0c;导致传输失败或者重新传输。为解决这一问题&#xff0c;断点续传技术应运而生。 一、断点续传技术是什么…

Ovis: 多模态大语言模型的结构化嵌入对齐

论文题目&#xff1a;Ovis: Structural Embedding Alignment for Multimodal Large Language Model 论文地址&#xff1a;https://arxiv.org/pdf/2405.20797 github地址&#xff1a;https://github.com/AIDC-AI/Ovis/?tabreadme-ov-file 今天&#xff0c;我将分享一项重要的研…

猫头虎 分享:MySQL 中 TEXT 与 LONGTEXT 数据类型详解与使用场景分析

今天猫头虎带大家深入探讨一番&#xff0c;关于 MySQL 中 TEXT 和 LONGTEXT 数据类型的区别与具体使用场景问题。最近有粉丝私信我说&#xff1a;“猫哥&#xff0c;TEXT 和 LONGTEXT 到底应该怎么选择啊&#xff1f;” 我相信很多开发者在面对 MySQL 中的这两个数据类型时&…

Scrapy框架原理与使用流程

一.Scrapy框架特点 框架&#xff08;Framework&#xff09;是一种软件设计方法&#xff0c;它提供了一套预先定义的组件和约定&#xff0c;帮助开发者快速构建应用程序。框架通常包括一组库、工具和约定&#xff0c;它们共同工作以简化开发过程。scrapy框架是python写的 为了爬…

C++的相关习题(2)

初阶模板 下面有关C中为什么用模板类的原因&#xff0c;描述错误的是? ( &#xff09; A.可用来创建动态增长和减小的数据结构 B.它是类型无关的&#xff0c;因此具有很高的可复用性 C.它运行时检查数据类型&#xff0c;保证了类型安全 D.它是平台无关的&#xff0c;可移植…

局部变量和全局变量(Python)

引入例子拆解 源码 class A:def __init__(self):self.test 0def add(c, k):c.test c.test 1k k 1def main():Count A()k 0for i in range(0, 25):add(Count, k)print("Count.test", Count.test)print("k", k)main() 运行结果如下图 代码解析 这…

HTML+JavaScript案例分享: 打造经典俄罗斯方块,详解实现全过程

在本文中,我们将深入探讨如何使用 JavaScript 实现经典的俄罗斯方块游戏。俄罗斯方块是一款广为人知的益智游戏,通过操纵各种形状的方块,使其在游戏区域内排列整齐,以消除完整的行来获得分数。 效果图如下: 一、游戏界面与布局 我们首先使用 HTML 和 CSS 来创建游戏的界面…

Uni-App-03

登录功能开发 实现POST提交 HTTP协议规定请求消息内容类型(Content-Type)有哪些&#xff1f;—— 只有四种 text/plain 没有编码的普通数据 application/x-www-form-urlencoded 编码后的普通数据 multipart/form-data 请求主体中包含文件上传域 application/json 请求主体是 J…

微信小程序版本更新管理——实现自动更新

✅作者简介&#xff1a;2022年博客新星 第八。热爱国学的Java后端开发者&#xff0c;修心和技术同步精进。 &#x1f34e;个人主页&#xff1a;Java Fans的博客 &#x1f34a;个人信条&#xff1a;不迁怒&#xff0c;不贰过。小知识&#xff0c;大智慧。 &#x1f49e;当前专栏…

js构造函数和原型对象,ES6中的class,四种继承方式

一、构造函数 1.构造函数是一种特殊的函数&#xff0c;主要用来初始化对象 2.使用场景 常见的{...}语法允许创建一个对象。可以通过构造函数来快速创建多个类似的对象。 const Peppa {name: 佩奇,age: 6,sex: 女}const George {name: 乔治,age: 3,sex: 男}const Mum {nam…

1 vsCode安装与使用

1 下载地址 Visual Studio Code - Code Editing. Redefined 2 安装 3 安装插件 安装完要重启 chinese:中文插件 open in browser &#xff1a;快速打开浏览器插件 ----------------------------------------------------------------------------------------------------- 重…

嵌入式学习-网络-Day02

嵌入式学习-网络-Day02 1.优化代码&#xff1a; 网络问题&#xff1a; 2.1虚拟机网络修复 2.2 网络调试 ping netstat 3.UDP编程 3.1通信流程 3.2函数接口 1.优化代码&#xff1a; 1.端口和ip地址通过命令行传参到代码中。 2.设置客户端退出&#xff0c;服务器结束循环接收。 通…

unity中GameObject介绍

在 Unity 中&#xff0c;Cube和Sphere等基本几何体是 Unity 引擎的内置预制体&#xff08;Prefabs&#xff09;&#xff0c;它们属于 Unity 中的GameObject 系统&#xff0c;可以在 Unity 的 Hierarchy 视图或 Scene 视图中右键点击&#xff0c;然后在弹出的菜单中选择 3D Obje…

论文阅读与写作入门

文章目录 1.阅读第一篇论文(1)论文结构(2)目标 2.使用GPT辅助论文的阅读与写作3.专有名词(1)架构(2)网络(3)机器学习 4.文献翻译软件5.从哪里下载文献&#xff1f;6.如何判断(你自己的)研究工作的价值or贡献【论文精读李沐】7.经典论文(1)AlexNet 2012(2)FCN 全卷积 2014(3)Res…

C++《vector的模拟实现》

在之前《vector》章节当中我们学习了STL当中的vector基本的使用方法&#xff0c;了解了vector当中各个函数该如何使用&#xff0c;在学习当中我们发现了vector许多函数的使用是和我们之前学习过的string类的&#xff0c;但同时也发现vector当中一些函数以及接口是和string不同的…

【纯血鸿蒙】HarmonyOS和OpenHarmony 的区别

一、开源鸿蒙&#xff08;Open Harmony&#xff09; 鸿蒙系统愿来的设计初衷&#xff0c;就是让所有设备都可以运行一个系统&#xff0c;但是每个设备的运算能力和功能都不同&#xff0c;所以内核的设计上&#xff0c;采用了微内核的设计&#xff0c;除了最基础的功能放在内核…

云岚到家 即刻体检 优惠卷管理 总结不熟练的点

多个条件的分页查询 public PageResult<ActivityInfoResDTO> queryPage(ActivityQueryForPageReqDTO reqDTO) {Page<Activity> pagequery new Page<>(reqDTO.getPageNo(),reqDTO.getPageSize());LambdaQueryWrapper<Activity> wrapper new LambdaQ…

C++ | Leetcode C++题解之第500题键盘行

题目&#xff1a; 题解&#xff1a; class Solution { public:vector<string> findWords(vector<string>& words) {vector<string> ans;string rowIdx "12210111011122000010020202";for (auto & word : words) {bool isValid true;cha…

数组实例之三子棋的实现(C语言)

目录 前言 一、三子棋实现的逻辑 二、三子棋的实现 2.1文件的创建添加 2.2 test文件基本逻辑 2.2.1菜单的实现 2.2.2菜单的选择 2.2.3game函数棋盘的实现 2.3game.c文件的编写 2.3.1初始化函数的模块 2.3.2棋盘打印的模块 2.3.3实现棋盘界面的打印 2.3.4实现玩家下…