文章目录
本次分享使用markdown,学习并练习这个语法可以快速的记录
一、那哪里是状态栏?为什么要封装状态栏工具呢?
- 状态栏是什么?在哪里?
- 状态栏是 手机最顶上的那一行,显示信号、时间、电量、网速等信息的区域。
- 如图所示,这就是手机的状态栏。
- 那为什么要封装状态栏呢?
- 当我们设置沉浸模式的时候,应用的背景色会与状态栏中内容的颜色相近,这会导致无法查看状态栏内容(比如说时间、wifi、信号、电量)
- 当然当我们封装了状态栏工具,就可以在不同的情境下使用不同的状态栏效果。
二、整体思路
1. 目的
在沉浸模式中我们可以通过状态栏工具,在不同的状态下使用不同的状态栏的效果
2. 封装工具选择
- 要满足特定情况下调用的效果---------interface / Function / class
- 要获取到上下文对象、获取窗口、设置状态栏-------Function
- 设置不同的属性,可以在不同的状态下调用
- 所以使用class比较合适
3.封装思路
- 导入包 window
- 创建类 StatusBar
- 首先为了方便后续设置不同的对象,我们要用函数 setWindowStatusBar 设置状态栏,这个函数的形参属性是window.SystemBarProperties
a、接收上下文对象 AppStorage
b、获取窗口 window.getTopWindow(a) 返回Promise
c、设置状态栏 b.setWindowSystemBarProperties(参数) - 通过函数设置不同的工具属性
- 实例化并导出,在不同的情境下使用
三、实现封装
1. 封装
a. 导入包 window
import { window } from '@kit.ArkUI'
b. 创建类 StatusBar
class StatusBar{}
c. 首先为了方便后续设置不同的对象,我们要用函数 setWindowStatusBar 设置状态栏,这个函数的形参属性是window.SystemBarProperties
- 首先我们要了解setSystemBarProperties
- setWindowSystemBarProperties(systemBarProperties: SystemBarProperties): Promise,
可以知道这个方法内需要传参,并参数类型为SystemBarProperties,返回的是一个Promise对象,所以可以使用async函数await - 通过文档我们也可以得知这个方法是可以设置主窗口三键导航栏、状态栏的属性,而我们今天要封装的就是这个状态栏的工具
- setWindowSystemBarProperties(systemBarProperties: SystemBarProperties): Promise,
名称 | 类型 | 说明 |
---|---|---|
statusBarColor | string | 状态栏背景颜色 |
statusBarContentColor | string | 状态栏文字颜色 |
- 同样我们也要了解一下参数SystemBarProperties
- 这是官方文档的内容我们只拿出需要的看一看
- 今天所封装所需要的功能可以用上这两个参数,当然SystemBarProperties中也可以设置别的,大家按需书写
- 代码部分
async getWindowStatus(config:window.SystemBarProperties){
// 获取上下文对象
const context = AppStorage.get<Context>('Context')!
// 获取应用窗口
const win = await window.getLastWindow(context)
// 设置状态栏
const A = await win.setWindowSystemBarProperties(config)
}
这里用到了Appstorage上下文对象,和获取应用窗口,那么其中的Context在获取并呗Appstorage传递到这里的呢?
在(QAQ) 这里的 3.获取上下问对象 中
d. 过函数设置不同的工具属性
// 深色字体
textDark(){
this.getWindowStatus({
statusBarContentColor:'#000000'
})
}
// 浅色字体
lightDark(){
this.getWindowStatus({
statusBarContentColor:'#ffffff'
})
}
// 状态栏颜色
StatusBarColor(){
this.getWindowStatus({
statusBarColor:'#282c34'
})
}
e. 实例化并导出
export const StatusBarconfig = new StatusBar()
2. 完整代码
import { window } from '@kit.ArkUI'
class StatusBar{
// 设置状态栏函数方便配置状态栏的属性
async getWindowStatus(config:window.SystemBarProperties){
// 获取上下文对象
const context = AppStorage.get<Context>('Context')!
// 获取应用窗口
const win = await window.getLastWindow(context)
// 设置状态栏
const A = await win.setWindowSystemBarProperties(config)
}
// 深色字体
textDark(){
this.getWindowStatus({
statusBarContentColor:'#000000'
})
}
// 浅色字体
lightDark(){
this.getWindowStatus({
statusBarContentColor:'#ffffff'
})
}
// 状态栏颜色
StatusBarColor(){
this.getWindowStatus({
statusBarColor:'#282c34'
})
}
}
export const StatusBarconfig = new StatusBar()