Parcourir la source

新增深色/浅色切换

chendeben il y a 1 an
Parent
commit
32224442fc

+ 36 - 0
entry/src/main/ets/MyAbilityStage.ets

@@ -0,0 +1,36 @@
+import AbilityStage from '@ohos.app.ability.AbilityStage';
+import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant';
+import dataStorage from '@ohos.data.storage';
+import hilog from '@ohos.hilog';
+
+export default class MyAbilityStage extends AbilityStage {
+  private storage: dataStorage.Storage | undefined = undefined;
+
+  async onCreate(): Promise<void> {
+    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
+    try {
+      // 获取存储实例
+      this.storage = await dataStorage.getStorage(this.context.cacheDir);
+      // 保存当前颜色模式
+      if (this.storage) {
+        await this.storage.put('currentColorMode', this.context.config.colorMode);
+        await this.storage.flush();
+      }
+    } catch (err) {
+      hilog.error(0x0000, 'testTag', 'Failed to initialize storage: %{public}s', err.message);
+    }
+  }
+
+  async onConfigurationUpdate(newConfig: import('@ohos.app.ability.Configuration').Configuration): Promise<void> {
+    try {
+      if (this.storage) {
+        // 更新颜色模式
+        await this.storage.put('currentColorMode', newConfig.colorMode);
+        await this.storage.flush();
+        hilog.info(0x0000, 'testTag', 'the newConfig.colorMode is %{public}s', JSON.stringify(newConfig.colorMode) ?? '');
+      }
+    } catch (err) {
+      hilog.error(0x0000, 'testTag', 'Failed to update color mode: %{public}s', err.message);
+    }
+  }
+} 

+ 88 - 3
entry/src/main/ets/pages/SettingPage.ets

@@ -5,6 +5,9 @@ import { AppUtil, PreferencesUtil } from '@pura/harmony-utils'
 import { Utility } from '../common/util/Utility'
 import { AvSessionController } from '../controller/AvSessionController'
 import { CustomContentDialog } from '@kit.ArkUI'
+import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant';
+import dataStorage from '@ohos.data.storage';
+import common from '@ohos.app.ability.common';
 // import { CustomDialog, CustomDialogController } from '@arkui/components'
 
 @Preview
@@ -24,6 +27,8 @@ export struct SettingPage {
   @State tempCoverApiUrl: string = ''
   @State coverApiUrl: string = PreferencesUtil.getStringSync('COVER_API', '')
   @State apiDialogType: 'lyric' | 'cover' = 'lyric'
+  @State isDarkMode: boolean = false // 是否启用深色模式
+  private storage: dataStorage.Storage | undefined = undefined;
   static readonly IS_BGPLAY_OPEN: string = 'isBgPlayOpen';
   static readonly IS_AUTO_RATATE: string = 'isAutoRatate';
   static readonly iS_MEMORY_PLAY: string = 'isMemoryPlay';
@@ -32,6 +37,7 @@ export struct SettingPage {
   static readonly iS_MUSIC_BG_COVER: string = 'isMusicBGCover';
   static readonly iS_SAVE_PLAY_MODE: string = 'isSavePlayMode';
   static readonly IS_COVER_RECTANGLE: string = 'isCoverRectangle'; //封面圆形或者方形
+  static readonly IS_DARK_MODE: string = 'isDarkMode'; // 深色模式设置
   @State titleBarModel: TitleBar.Model = new TitleBar.Model()
     .setTitleTextStyle(FontStyle.Normal)
     .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
@@ -104,13 +110,24 @@ export struct SettingPage {
   }
 
   // 组件生命周期
-  aboutToAppear() {
+  async aboutToAppear() {
     this.isBgPlayOpen = PreferencesUtil.getBooleanSync(SettingPage.IS_BGPLAY_OPEN, true)
     this.isAutoRatate = PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_RATATE, true)
     this.isMemoryPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_PLAY, true)
     this.isMediacodec = PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN, false)
     this.isMusicMemoryPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)
     this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
+    
+    try {
+      const context = getContext(this) as common.UIAbilityContext;
+      this.storage = await dataStorage.getStorage(context.cacheDir);
+      if (this.storage) {
+        const colorMode = await this.storage.get('currentColorMode', ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT);
+        this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK;
+      }
+    } catch (err) {
+      console.error('Failed to get color mode:', err);
+    }
   }
 
   // 组件生命周期
@@ -118,10 +135,78 @@ export struct SettingPage {
     // 无需处理apiDialogController
   }
 
+  // 切换深色模式
+  async toggleDarkMode(checked: boolean) {
+    try {
+      if (this.storage) {
+        const newMode = checked ? ConfigurationConstant.ColorMode.COLOR_MODE_DARK : ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT;
+        await this.storage.put('currentColorMode', newMode);
+        await this.storage.flush();
+        this.isDarkMode = checked;
+        
+        // 通知系统更新颜色模式
+        const context = getContext(this) as common.UIAbilityContext;
+        context.getApplicationContext().setColorMode(newMode);
+        
+        // 显示提示
+        this.getUIContext().getPromptAction().showToast({
+          message: checked ? '已切换到深色模式' : '已切换到浅色模式',
+          duration: 2000,
+          showMode: promptAction.ToastShowMode.TOP_MOST,
+          bottom: 85
+        });
+      }
+    } catch (err) {
+      console.error('Failed to update color mode:', err);
+    }
+  }
+
   build() {
     Column() {
       TitleBar({ model: $titleBarModel })
       Column() {
+        // 主题设置
+        Row() {
+          Text('主题设置')
+            .margin({ left: 38, right: 20 })
+            .fontSize(16)
+            .fontColor(Color.Gray)
+            .fontWeight(480)
+          Blank()
+        }
+        .width('100%')
+        .height(55)
+
+        Line().width('100%').height(0.3).backgroundColor($r('app.color.index_tab_unselected_font_color'))
+        
+        // 深色模式开关
+        Row() {
+          Image($r('app.media.kp_music_nor'))
+            .width(22)
+            .height(22)
+            .alignSelf(ItemAlign.Center)
+            .margin({ left: 28 })
+          Text('深色模式')
+            .margin({ left: 10, right: 20 })
+            .fontSize(15)
+            .fontColor(Color.Gray)
+            .fontWeight(480)
+          Blank()
+          Toggle({ type: ToggleType.Switch, isOn: this.isDarkMode })
+            .selectedColor($r('app.color.title_bar_bg'))
+            .switchPointColor(Color.White)
+            .margin({ right: 28 })
+            .onChange((checked: boolean) => {
+              this.toggleDarkMode(checked);
+            })
+            .width(50)
+            .height(30);
+        }
+        .width('100%')
+        .height(55)
+
+        Line().width('100%').height(0.3).backgroundColor($r('app.color.index_tab_unselected_font_color'))
+
         //音频设置
         Row() {
           Text('音频设置')
@@ -256,7 +341,7 @@ export struct SettingPage {
         .margin({ top: 8, bottom: 12 })
 
       }
-      .backgroundColor(Color.White)
+      .backgroundColor(this.isDarkMode ? '#1E1E1E' : Color.White)
       .margin({
         left: 15,
         right: 15,
@@ -265,7 +350,7 @@ export struct SettingPage {
       })
       .borderRadius(30)
     }
-    .backgroundColor($r('app.color.index_background'))
+    .backgroundColor(this.isDarkMode ? '#121212' : $r('app.color.index_background'))
     .height('100%')
   }
 

+ 29 - 1
entry/src/main/ets/pages/index.ets

@@ -14,10 +14,38 @@
  */
 
 import router from '@ohos.router'
+import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant';
+import dataStorage from '@ohos.data.storage';
+import common from '@ohos.app.ability.common';
 
 @Entry
 @Component
 struct indexPage {
+  @State currentMode: number = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT;
+  private storage: dataStorage.Storage | undefined = undefined;
+
+  async aboutToAppear() {
+    try {
+      const context = getContext(this) as common.UIAbilityContext;
+      this.storage = await dataStorage.getStorage(context.cacheDir);
+      if (this.storage) {
+        const colorMode = await this.storage.get('currentColorMode', this.currentMode);
+        this.currentMode = colorMode as number;
+        this.updateUI();
+      }
+    } catch (err) {
+      console.error('Failed to get color mode:', err);
+    }
+  }
+
+  updateUI() {
+    if (this.currentMode == ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT) {
+      console.info('当前为浅色模式');
+    } else {
+      console.info('当前为深色模式');
+    }
+  }
+
   build() {
     Column() {
       Button($r('app.string.video_demo'))
@@ -34,7 +62,7 @@ struct indexPage {
     }
     .width('100%')
     .height('100%')
-    .backgroundColor(Color.Gray)
+    .backgroundColor(this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT ? Color.Gray : '#121212')
     .justifyContent(FlexAlign.Center)
   }
 }

+ 108 - 0
entry/src/main/resources/dark/element/color.json

@@ -0,0 +1,108 @@
+{
+  "color": [
+    {
+      "name": "start_window_background",
+      "value": "#121212"
+    },
+    {
+      "name": "silvery",
+      "value": "#1E1E1E"
+    },
+    {
+      "name": "white",
+      "value": "#FFFFFF"
+    },
+    {
+      "name": "touming",
+      "value": "#00FFFFFF"
+    },
+    {
+      "name": "ban_touming",
+      "value": "#00000000"
+    },
+    {
+      "name": "title_bar_bg",
+      "value": "#FF4081"
+    },
+    {
+      "name": "index_background",
+      "value": "#121212"
+    },
+    {
+      "name": "tab_bar_sel",
+      "value": "#55ceac"
+    },
+    {
+      "name": "tab_bar_normal",
+      "value": "#2C2C2C"
+    },
+    {
+      "name": "index_tab_font_color",
+      "value": "#FFFFFF"
+    },
+    {
+      "name": "index_tab_selected_font_color",
+      "value": "#007DFF"
+    },
+    {
+      "name": "index_tab_unselected_font_color",
+      "value": "#666666"
+    },
+    {
+      "name": "index_tab_local_list_font_color",
+      "value": "#999999"
+    },
+    {
+      "name": "divider_color",
+      "value": "#333333"
+    },
+    {
+      "name": "button_back_ground_color",
+      "value": "#007DFF"
+    },
+    {
+      "name": "dodgerBlue",
+      "value": "#1E90FF"
+    },
+    {
+      "name": "RoyalBlue",
+      "value": "#4169E1"
+    },
+    {
+      "name": "track_color",
+      "value": "#333333"
+    },
+    {
+      "name": "speed_text_color",
+      "value": "#999999"
+    },
+    {
+      "name": "btn_green",
+      "value": "#55ceac"
+    },
+    {
+      "name": "pri_bg",
+      "value": "#1E1E1E"
+    },
+    {
+      "name": "orange",
+      "value": "#FF8C00"
+    },
+    {
+      "name": "line_blue",
+      "value": "#00cccc"
+    },
+    {
+      "name": "btn_red",
+      "value": "#ff6b47"
+    },
+    {
+      "name": "slider_track",
+      "value": "#33FFFFFF"
+    },
+    {
+      "name": "select_swiper",
+      "value": "#DBFFFFFF"
+    }
+  ]
+}