HarmonyOS 如何在应用中动态的设置深浅色模式?

阅读 600
1 个回答

配置组件颜色后,组件颜色不跟随系统主题配色切换,框架定义了两种颜色模式,取值如下:

dark:深色模式

light:浅色模式

应用开发中使用的各类资源文件,需要放入特定子目录中存储管理。resources目录包括三大类目录,一类为base目录,一类为限定词目录,还有一类为rawfile目录。自定义深浅色模式的资源文件夹属于限定词目录。

创建深浅色模式资源:

右键点击resources文件夹,新建"Resource Directory"

在弹出框内选择"Color Mode"选项,新建Light/Dark资源文件夹

右键点击Light/Dark资源文件夹中的element文件夹,新建"Element Resource File"

在弹出框内选择"Root element"为"color"类型,创建颜色资源文件

深浅色资源文件格式如下:

{ 
  "color": [ 
  { 
    "name": "start_window_background", 
  "value": "#FFFFFF" 
  }, 
  { 
    "name": "background", 
  "value": "#FFFFFF" 
  }, 
  { 
    "name": "font_color", 
  "value": "#FFFFFF" 
  }, 
  { 
    "name": "button_background", 
  "value": "#0000FF" 
  } 
  ] 
}

未配置Light/Dark颜色文件时,应用默认使用base资源目录下的颜色文件

提供一下代码进行参考:

demo:应用中使用$r符号取用资源文件

// 对单个页面进行设置 
import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; 
 
@Entry 
@Component 
struct ForceSetExample { 
  onPageShow() { 
    let applicationContext = getContext().getApplicationContext(); 
    applicationContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK); 
  } 
 
  onPageHide() { 
    let applicationContext = getContext().getApplicationContext(); 
    applicationContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT); 
    applicationContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET); 
  } 
 
  build() { 
    Column() { 
      Text('进入页面强制设置为深色模式').fontSize(25).margin(15) 
      Text('退出页面时先设置为浅色模式').fontSize(25).margin(15) 
      Text('再设置为跟随系统').fontSize(25).margin(15) 
      Search({ placeholder: 'Type to search...' }) 
        .searchButton('SEARCH') 
        .width(400) 
        .height(40) 
        .placeholderFont({ size: 14, weight: 400 }) 
        .textFont({ size: 14, weight: 400 }) 
        .margin(20) 
 
      Button('按钮一') 
        .width('50%').margin('10%').backgroundColor($r('app.color.background')) 
      Button('按钮二') 
        .width('50%').margin('10%') 
    }.width('100%') 
  } 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进