首选项
简介
本示例使用@ohos.data.preferences接口,展示了使用首选项持久化存储数据的功能。
效果预览
使用说明
1.点击顶部titleBar的右侧切换按钮,弹出主题菜单,选择任意主题则切换相应的主题界面;
2.退出应用再重新进入,显示上一次退出前的主题界面。
具体实现
- 切换主题:在首页预先设置好几套主体数据,使用preferences.getPreferences获取使用Preferences对象,调用Preferences.get() 读取缓存中的参数,得到当前应该展示哪一套主体。每次点击切换按钮都会调用Preferences.put()来重新修改参数,然后使用 Preferences.flush()保存并刷新文件内容。 源码参考:[Index.ets] 。
/** Copyright (c) 2024 Huawei Device Co., Ltd.* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import { emitter } from '@kit.BasicServicesKit';
import { preferences } from '@kit.ArkData';
import Logger from '../model/Logger';
import ThemeDesktop from '../common/ThemeDesktop';export interface ImageAndName {image: Resource;name: string;
}const THEMES: Array<ImageAndName>[] = [[{ image: $r('app.media.dialer'), name: '电话' },{ image: $r('app.media.shopping'), name: '商城' },{ image: $r('app.media.notes'), name: '备忘录' },{ image: $r('app.media.settings'), name: '设置' },{ image: $r('app.media.camera'), name: '相机' },{ image: $r('app.media.gallery'), name: '相册' },{ image: $r('app.media.music'), name: '音乐' },{ image: $r('app.media.video'), name: '视频' },],[{ image: $r('app.media.simplicityCall'), name: '电话' },{ image: $r('app.media.simplicityShop'), name: '商城' },{ image: $r('app.media.simplicityNotes'), name: '备忘录' },{ image: $r('app.media.simplicitySetting'), name: '设置' },{ image: $r('app.media.simplicityCamera'), name: '相机' },{ image: $r('app.media.simplicityPhotos'), name: '相册' },{ image: $r('app.media.simplicityMusic'), name: '音乐' },{ image: $r('app.media.simplicityVideo'), name: '视频' },],[{ image: $r('app.media.pwcall'), name: '电话' },{ image: $r('app.media.pwshop'), name: '商城' },{ image: $r('app.media.pwnotes'), name: '备忘录' },{ image: $r('app.media.pwsetting'), name: '设置' },{ image: $r('app.media.pwcamera'), name: '相机' },{ image: $r('app.media.pwphotos'), name: '相册' },{ image: $r('app.media.pwmusic'), name: '音乐' },{ image: $r('app.media.pwvideo'), name: '视频' },]
]
const TAG: string = '[Index]';
const PREFERENCES_NAME = 'theme.db';
const THEME_NAMES: string[] = ['default', 'simplicity', 'pomeloWhtie'];
let preferenceTheme: preferences.Preferences | null = null;@Entry
@Component
struct Index {@State nowTheme: string = '';@State themeDatas: Array<ImageAndName> = [];async aboutToAppear() {//从内存中获取轻量级存储db文件await this.getPreferencesFromStorage()//从轻量级存储db文件中获取键名为theme的键值this.nowTheme = await this.getPreference()console.info(`nowTheme__get ${this.nowTheme}`)emitter.emit({ eventId: 0, priority: 0 }, {data: {nowTheme: this.nowTheme}})let index = THEME_NAMES.indexOf(this.nowTheme)this.themeDatas = THEMES[index]}async getPreferencesFromStorage() {let context = getContext(this) as ContextpreferenceTheme = await preferences.getPreferences(context, PREFERENCES_NAME)}async putPreference(data: string) {Logger.info(TAG, `Put begin`)if (preferenceTheme !== null) {await preferenceTheme.put('theme', data)await preferenceTheme.flush()}}async getPreference(): Promise<string> {Logger.info(TAG, `Get begin`)let theme: string = ''if (preferenceTheme !== null) {theme = await preferenceTheme.get('theme', 'default') as string;return theme;}return theme;}changeTheme(themeNum: number) {this.themeDatas = THEMES[themeNum];this.putPreference(THEME_NAMES[themeNum]);}build() {Column() {Row() {Text($r('app.string.MainAbility_label')).fontSize(25).layoutWeight(5).padding({ left: 10 }).fontColor(Color.White).fontWeight(FontWeight.Bold)Image($r('app.media.change')).key('changeBtn').id('changeBtn').height(30).layoutWeight(1).objectFit(ImageFit.ScaleDown).bindMenu([{value: THEME_NAMES[0],action: () => {this.changeTheme(0)}},{value: THEME_NAMES[1],action: () => {this.changeTheme(1)}},{value: THEME_NAMES[2],action: () => {this.changeTheme(2)}}])}.width('100%').height(50).backgroundColor('#0D9FFB')ThemeDesktop({ themeDatas: $themeDatas })}.width('100%').height('100%')}
}
以上就是本篇文章所带来的鸿蒙开发中一小部分技术讲解;想要学习完整的鸿蒙全栈技术。可以在结尾找我可全部拿到!
下面是鸿蒙的完整学习路线,展示如下:
除此之外,根据这个学习鸿蒙全栈学习路线,也附带一整套完整的学习【文档+视频】,内容包含如下:
内容包含了:(ArkTS、ArkUI、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、鸿蒙南向开发、鸿蒙项目实战)等技术知识点。帮助大家在学习鸿蒙路上快速成长!
鸿蒙【北向应用开发+南向系统层开发】文档
鸿蒙【基础+实战项目】视频
鸿蒙面经
为了避免大家在学习过程中产生更多的时间成本,对比我把以上内容全部放在了↓↓↓想要的可以自拿喔!谢谢大家观看!