Просмотр исходного кода

主题模式新增跟随系统

chendeben 1 год назад
Родитель
Сommit
3b96ccf594

+ 14 - 35
entry/src/main/ets/pages/NewIndex.ets

@@ -106,6 +106,7 @@ struct NewIndex{
   @Provide isHistory:boolean =  false
   /** 是否可以返回上一级 */
   @Provide isCanBack:boolean=  false
+  @StorageProp('currentColorMode') currentMode: number = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT;
 
   /**
    * 一多界面适配断点系统
@@ -157,41 +158,19 @@ struct NewIndex{
    * - 初始化图片缓存
    * - 判断是否显示赞助入口
    */
-  async aboutToAppear() {
-
-    Utility.enableFullScreen()
-
-    this.breakpointSystem.register();
-    let params = router.getParams() as Record<string, Object>;
-    this.videoLocalList = params.videoList as VideoItem[];
-    Utility.setStatusBarLight()
-    // ScreenUtil 设置屏幕尺寸信息
-    ScreenUtil.setScreenSize();
-    this.bundleName =   AppUtil.getBundleName()
-    this.versionName =  AppUtil.getVersionName();
-    // 初始化图片缓存
-    await ImageKnife.getInstance().initFileCache(this.context, 256, 256 * 1024 * 1024)
-    // 判断是否显示赞助入口
-    this.isShowSponsorship = Utility.isOpenTime()
-
-    // 初始化深色模式状态
-    try {
-      // 从持久化存储中读取深色模式设置
-      const savedDarkMode = PreferencesUtil.getBooleanSync(SettingPage.IS_DARK_MODE, false);
-      this.isDarkMode = savedDarkMode;
-
-      // 更新 AppStorage 中的颜色模式
-      const colorMode = savedDarkMode ? ConfigurationConstant.ColorMode.COLOR_MODE_DARK : ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT;
-      AppStorage.setOrCreate('currentColorMode', colorMode);
-      AppStorage.setOrCreate('isDarkMode', savedDarkMode);
-
-      // 通知系统更新颜色模式
-      const context = getContext(this) as common.UIAbilityContext;
-      context.getApplicationContext().setColorMode(colorMode);
-    } catch (err) {
-      console.error('Failed to initialize color mode:', err);
-    }
-  }
+
+async aboutToAppear() {
+  Utility.enableFullScreen()
+  this.breakpointSystem.register();
+  let params = router.getParams() as Record<string, Object>;
+  this.videoLocalList = params.videoList as VideoItem[];
+  Utility.setStatusBarLight()
+  ScreenUtil.setScreenSize();
+  this.bundleName =   AppUtil.getBundleName()
+  this.versionName =  AppUtil.getVersionName();
+  await ImageKnife.getInstance().initFileCache(this.context, 256, 256 * 1024 * 1024)
+  this.isShowSponsorship = Utility.isOpenTime()
+}
 
   /**
    * 页面消失生命周期钩子

+ 55 - 35
entry/src/main/ets/pages/SettingPage.ets

@@ -37,6 +37,8 @@ export struct SettingPage {
   @State tempCoverApiUrl: string = ''
   @State coverApiUrl: string = PreferencesUtil.getStringSync('COVER_API', '')
   @State apiDialogType: 'lyric' | 'cover' = 'lyric'
+  @State themeMode: number = 0 // 0: 跟随系统, 1: 浅色, 2: 深色
+  static readonly THEME_MODE: string = 'themeMode';
   static readonly SORT_TYPE: string = 'musicSortType';
   @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT;
   @StorageLink('isDarkMode') isDarkMode: boolean = false // 是否启用深色模式
@@ -149,6 +151,8 @@ export struct SettingPage {
     const savedDarkMode = PreferencesUtil.getBooleanSync(SettingPage.IS_DARK_MODE, false);
     this.isDarkMode = savedDarkMode;
     this.currentMode = savedDarkMode ? ConfigurationConstant.ColorMode.COLOR_MODE_DARK : ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT;
+    this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
+    this.applyThemeMode(this.themeMode)
     AppStorage.setOrCreate('currentColorMode', this.currentMode);
     AppStorage.setOrCreate('isDarkMode', this.isDarkMode);
   }
@@ -161,38 +165,25 @@ export struct SettingPage {
     PreferencesUtil.putSync(SettingPage.IS_DARK_MODE, this.isDarkMode);
   }
 
-  // 切换深色模式
-  async toggleDarkMode(checked: boolean) {
-    try {
-      const newMode = checked ? ConfigurationConstant.ColorMode.COLOR_MODE_DARK : ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT;
-
-      // 更新 AppStorage 中的颜色模式
-      AppStorage.setOrCreate('currentColorMode', newMode);
-      AppStorage.setOrCreate('isDarkMode', checked);
-
-      // 保存深色模式设置到持久化存储
-      PreferencesUtil.putSync(SettingPage.IS_DARK_MODE, 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);
-    }
-  }
 
   // 组件生命周期
   aboutToDisappear() {
     // 无需处理apiDialogController
   }
+  applyThemeMode(mode: number) {
+    let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
+    if (mode === 1) {
+      colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
+    } else if (mode === 2) {
+      colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
+    }
+    AppStorage.setOrCreate('currentColorMode', colorMode)
+    AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
+    PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
+    // 只有强制浅色/深色时才主动设置
+    const context = getContext(this) as common.UIAbilityContext
+    context.getApplicationContext().setColorMode(colorMode)
+  }
 
   build() {
     Column() {
@@ -218,22 +209,51 @@ export struct SettingPage {
             .height(48)
             Line().width('100%').height(0.3).backgroundColor($r('app.color.index_tab_unselected_font_color'))
             // 深色模式
+            // Row() {
+            //   Text('深色模式')
+            //     .margin({ left: 18 })
+            //     .fontSize(15)
+            //     .fontColor(Color.Gray)
+            //     .fontWeight(480)
+            //     .layoutWeight(1)
+            //   Toggle({ type: ToggleType.Switch, isOn: this.isDarkMode })
+            //     .selectedColor($r('app.color.tab_item_bg'))
+            //     .switchPointColor(Color.White)
+            //     .margin({ right: 18 })
+            //     .onChange((checked: boolean) => {
+            //       this.toggleDarkMode(checked);
+            //     })
+            //     .width(50)
+            //     .height(30);
+            // }
+            // .height(55)
             Row() {
-              Text('深色模式')
+              Text('主题模式')
                 .margin({ left: 18 })
                 .fontSize(15)
                 .fontColor(Color.Gray)
                 .fontWeight(480)
                 .layoutWeight(1)
-              Toggle({ type: ToggleType.Switch, isOn: this.isDarkMode })
-                .selectedColor($r('app.color.tab_item_bg'))
-                .switchPointColor(Color.White)
+              Select([
+                { value: '跟随系统' },
+                { value: '浅色' },
+                { value: '深色' }
+              ])
+                .font({ size: 15, weight: FontWeight.Medium })
+                .fontColor(Color.Gray)
                 .margin({ right: 18 })
-                .onChange((checked: boolean) => {
-                  this.toggleDarkMode(checked);
+                .selected(this.themeMode)
+                .value(['跟随系统', '浅色', '深色'][this.themeMode])
+                .onSelect((_index: number) => {
+                  this.themeMode = _index
+                  this.applyThemeMode(_index)
+                  this.getUIContext().getPromptAction().showToast({
+                    message: ['已切换为跟随系统', '已切换为浅色', '已切换为深色'][_index],
+                    duration: 2000,
+                    showMode: promptAction.ToastShowMode.TOP_MOST,
+                    bottom: 85
+                  })
                 })
-                .width(50)
-                .height(30);
             }
             .height(55)
 

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

@@ -15,36 +15,11 @@
 
 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('当前为深色模式');
-    }
-  }
+  @StorageProp('currentColorMode') currentMode: number = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT;
 
   build() {
     Column() {