鸿蒙开发-自定义状态栏颜色

271 阅读1分钟

自定义状态栏,首先设置为全屏,然后获取状态栏的高度,最后填充指定的颜色即可。

Screenshot_20240111_221431_com.example.myapplicat.jpg entryability中获取窗口

async onWindowStageCreate(windowStage: window.WindowStage) {
  // 获取设备信息
  GlobalContext.getContext().setObject('display', await display.getDefaultDisplaySync())
  windowStage.getMainWindow((err, windowClass) => {
    windowClass.setWindowLayoutFullScreen(true)
    // 隐藏状态栏显示
    // windowClass.setWindowSystemBarEnable(['navigation'])
    const avoidAreaData = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM)
    GlobalContext.getContext().setObject('avoidAreaData', avoidAreaData)
  })
  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;
    }
  });
}

自定义状态栏颜色

import { GlobalContext } from '../../common/utils/GlobalContext'
import window from '@ohos.window'

@Component
export default struct Home {
  @State barStatusHeight:number = (GlobalContext.getContext().getObject('avoidAreaData') as window.AvoidArea).topRect.height
  build() {
    Column() {
      Column()
        .width('100%')
        .height(px2vp(this.barStatusHeight))
        .backgroundColor('#2ca5ff')
    }.width('100%').height('100%')
    .backgroundColor(Color.Pink)
  }
}

getWindowAvoidArea

getWindowAvoidArea(type: AvoidAreaType): AvoidArea;

获取窗口内容规避的区域,如系统的系统栏区域、凹凸区域。使用callback异步回调。

type:

TYPE_SYSTEM:表示系统默认区域

TYPE_CUTOUT:表示刘海屏区域。

setWindowLayoutFullScreen

setWindowLayoutFullScreen(isLayoutFullScreen: boolean): Promise<void>;

设置窗口的布局是否为全屏显示状态。注意,状态栏此时没有隐藏。

setWindowSystemBarEnable

setWindowSystemBarEnable(names: Array<'status' | 'navigation'>): Promise<void>;

设置导航栏、状态栏的可见模式