本案例在页面与数据案例的基础上,实现应用“我的”页面的字体大小调节。
一、案例实现
(一) 案例效果截图
(二) 案例运用的知识点
- 字体大小调节原理:通过组件Slider滑动,获取滑动数值,将这个值通过首选项进行持久化,页面的字体通过这个值去改变大小。
- 首选项:首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。
- 自定义弹窗:应用promptAction.openCustomDialog来定义弹窗。
- 全局UI状态存储:通过AppStorageV2实现此功能。
(三) 给"我的"组件添加功能
- Setting组件改造
// entry/src/main/ets/view/Setting.ets
import ItemData from '../viewmodel/ItemData'
import mainViewModel from '../viewmodel/MainViewModel'
import { SliderCustomDialog } from './SliderCustomDialog'
import { FontSizeStorage } from '../model/FontSizeStorage'
import { AppStorageV2, promptAction } from '@kit.ArkUI'
/**
* 设置选项卡内容组件
*/
@ComponentV2
export default struct Setting {
// 自定义弹窗组件的 ID
@Local customDialogComponentId: number = 0
// 连接 AppStorage 中的字体大小存储对象
@Local storage: FontSizeStorage = AppStorageV2.connect(
FontSizeStorage,
'storage',
() => new FontSizeStorage()
)!
/**
* 构建自定义弹窗组件(用于调整字体大小)
*/
@Builder
customDialogComponent() {
SliderCustomDialog({
customDialogComponentId: this.customDialogComponentId
})
}
/**
* 构建单个设置项 Cell
* @param item 每一个设置项的数据
*/
@Builder
settingCell(item: ItemData) {
Row() {
Row({}) {
// 设置项图标
Image(item.img)
.height('22vp')
.margin({ left: '16vp', right: '12vp' })
// 设置项标题,根据字体偏移调整字号
Text(item.title)
.fontSize(`${16 + this.storage.fontSizeOffset}fp`)
}
// 设置项右侧图标:如果有特殊项则显示开关 Toggle,否则显示箭头图标
if (item.others === undefined) {
Image($r('app.media.right_grey'))
.width('12vp')
.height('24vp')
} else {
Toggle({ type: ToggleType.Switch, isOn: false })
}
}
// 点击事件:如果 item.id === 1,打开自定义弹窗(如字体大小设置)
.onClick(() => {
if (item.id === 1) {
promptAction.openCustomDialog({
builder: () => {
this.customDialogComponent()
},
alignment: DialogAlignment.Bottom
}).then((dialogId: number) => {
this.customDialogComponentId = dialogId
})
}
})
.justifyContent(FlexAlign.SpaceBetween)
.width('100%')
.padding({ left: '8vp', right: '22vp' })
}
/**
* 构建组件主体 UI
*/
build() {
Scroll() {
Column({ space: 12 }) {
// 设置页面标题
Text($r('app.string.mainPage_tabTitles_mine'))
.width('100%')
.margin({ top: '48vp' })
.fontWeight(700)
.fontSize(`${26 + this.storage.fontSizeOffset}fp`)
// 用户头像与账户信息
Row() {
Image($r('app.media.account'))
.width('48vp')
.height('48vp')
Column() {
Text($r('app.string.setting_account_name'))
.fontSize(`${20 + this.storage.fontSizeOffset}fp`)
Text($r('app.string.setting_account_email'))
.fontSize(`${12 + this.storage.fontSizeOffset}fp`)
.margin({ top: '4vp' })
}
.alignItems(HorizontalAlign.Start)
.margin({ left: '12vp' })
}
.alignItems(VerticalAlign.Center)
.width('100%')
// 设置项列表
List({ space: 12 }) {
// 多组设置项
ForEach(mainViewModel.getSettingListData(), (item: ItemData[]) => {
ListItemGroup() {
// 遍历每组设置项
ForEach(item, (cell: ItemData) => {
ListItem() {
this.settingCell(cell)
}
.height('48vp')
})
}
// 每组之间添加分隔线与圆角背景
.divider({
strokeWidth: '1vp',
color: '#0d000000',
startMargin: '42vp',
endMargin: '24vp'
})
.backgroundColor('#ffffff')
.borderRadius('16vp')
}, (item: ItemData) => JSON.stringify(item))
}
.scrollBar(BarState.Off)
.width('100%')
.padding({ top: '4vp', bottom: '4vp' })
// 空白占位符
Blank()
// 页面底部按钮(如退出登录)
Button($r('app.string.setting_button'), { type: ButtonType.Capsule })
.width('90%')
.height('40vp')
.fontSize(`${16 + this.storage.fontSizeOffset}fp`)
.fontColor('#FA2A2D')
.fontWeight(FontWeight.Medium)
.backgroundColor('#E5E8EA')
.margin({ bottom: '16vp' })
}
.height('100%')
}
.width('100%')
.height('100%')
}
}
关键代码说明:
- @Builder customDialogComponent(),通过在组件内部定义openCustomDialog函数的builder属性值,builder函数渲染的弹窗组件定义在SliderCustomDialog模块里。
- .fontSize(
${16 + this.storage.fontSizeOffset}fp),当全局状态变量fontSizeOffset更新时,这里能读取到最新的值。注意这个值只保存在内存中,还需要Preferences来实现永久的存贮。
- 全局状态存储对象
// entry/src/main/ets/model/FontSizeStorage.ets
@ObservedV2
export class FontSizeStorage {
@Trace fontSizeOffset: number = 0
}
(四) 弹窗组件
// entry/src/main/ets/view/SliderCustomDialog.ets
import preferenceUtilsObject from "../common/database/PreferencesUtil"
import { AppStorageV2, promptAction } from '@kit.ArkUI'
import { FontSizeStorage } from '../model/FontSizeStorage'
/**
* 字体大小调整弹窗组件
*/
@ComponentV2
export struct SliderCustomDialog {
// 弹窗组件 ID,用于关闭弹窗
@Param customDialogComponentId: number = 0
// 当前滑块值(字体偏移值)
@Local currentValue: number = 0
// 连接字体大小存储对象,绑定 AppStorage 实现数据共享与刷新
@Local storage: FontSizeStorage = AppStorageV2.connect(
FontSizeStorage, 'storage', () => new FontSizeStorage()
)!
build() {
Column() {
// 弹窗标题:字体大小设置
Text($r('app.string.fontsize_change'))
.font({
size: '20fp',
weight: 700
})
.textAlign(TextAlign.Center)
.opacity(0.9)
.width('312vp')
.height('27vp')
.margin({
top: '15vp',
bottom: '15vp',
left: '24vp',
right: '24vp'
})
// 滑块设置区域:包含 A - 滑块 - A
Row() {
// 小字号预览
Text('A')
.font({
size: '12fp',
weight: 700
})
.margin({ right: '4vp' })
// 字体偏移滑块组件
Slider({
value: this.storage.fontSizeOffset, // 绑定当前存储的字体偏移值
min: -4, // 最小偏移
max: 4 // 最大偏移
})
.margin({ right: '4vp' })
.width('304vp')
.onChange((data: number) => {
this.currentValue = data // 实时记录滑动中的偏移值
})
// 大字号预览
Text('A')
.font({
size: '20fp',
weight: 700
})
}
// 底部操作按钮区域
Row() {
// 取消按钮:关闭弹窗
Button($r('app.string.Cancel'))
.width('156vp')
.height('41vp')
.margin({ left: '16vp', right: '16vp' })
.backgroundColor('#0d000000')
.fontColor('#0A59F7')
.onClick(() => {
promptAction.closeCustomDialog(this.customDialogComponentId)
})
// 确认按钮:保存设置并关闭弹窗
Button($r('app.string.Confirmed'))
.width('156vp')
.height('41vp')
.margin({ right: '16vp' })
.onClick(() => {
// 保存当前字体偏移值到 Preferences 持久化
preferenceUtilsObject.saveChangeFontSize(this.currentValue)
// 同时更新 AppStorage 中的绑定值,触发全局刷新
this.storage.fontSizeOffset = this.currentValue
// 关闭弹窗
promptAction.closeCustomDialog(this.customDialogComponentId)
})
}
.width('100%')
.margin({ top: '15vp', bottom: '15vp' })
}
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
.width('360vp')
.backgroundColor('#ffffff')
.borderRadius('16vp')
}
}
关键代码说明:
- @Param customDialogComponentId,接收父组件传递过来的弹窗ID,用于关闭弹窗。
- 单击“确认”按钮时,通过Preferences持久存储字号大小,同时更新storage。
(五) 首选项工具类实现
// entry/src/main/ets/common/database/PreferencesUtil.ets
import { preferences } from '@kit.ArkData'
import { BusinessError } from '@kit.BasicServicesKit'
import { hilog } from '@kit.PerformanceAnalysisKit'
// 用于记录字体大小偏移量的键名
const KEY_APP_FONT_SIZE = 'appFontSize'
// 日志标签
const TAG = 'PreferencesUtil'
/**
* PreferencesUtil 类提供偏好设置的创建、保存和查询方法
*/
export class PreferencesUtil {
preference?: preferences.Preferences
/**
* 创建偏好设置实例的方法
* @param context 当前应用上下文
*/
getFontPreferences(context: Context) {
// 创建名为 FontPreferences 的偏好设置实例
this.preference = preferences.getPreferencesSync(
context,
{ name: 'FontPreferences' }
)
hilog.info(0x0000, TAG, 'create success')
}
/**
* 保存字体大小偏移量的方法
* @param fontSizeOffset 要保存的偏移值
*/
saveChangeFontSize(fontSizeOffset: number) {
// 将偏移值写入偏好设置
this.preference?.putSync(KEY_APP_FONT_SIZE, fontSizeOffset)
// 刷新偏好设置,确保数据持久化
this.preference?.flush(
(err: BusinessError) => {
if (err) {
hilog.error(0x0000, TAG, '刷新失败,错误码='
+ err.code + ',错误信息=' + err.message)
return
}
hilog.info(0x0000, TAG, '刷新成功')
})
}
/**
* 获取字体大小偏移量的方法
* @returns 偏移量(number)
*/
getChangeFontSize() {
let fontSizeOffset: number = 0
// 读取偏好设置中的字体大小偏移值,如果不存在则默认为0
fontSizeOffset = this.preference?.getSync(KEY_APP_FONT_SIZE, 0) as number
return fontSizeOffset
}
/**
* 判断偏好设置中是否存在对应键的方法
* @returns 是否存在对应键(boolean)
*/
isKeyExist(): boolean {
let isKeyExist: boolean = false
// 异步检查键是否存在,结果回调中赋值,但该方法同步返回,结果可能不准确
this.preference?.has(KEY_APP_FONT_SIZE).then(async (isExist: boolean) => {
isKeyExist = isExist
}).catch((err: Error) => {
hilog.error(0x0000, TAG, '检查键是否存在失败,错误信息: ' + err)
})
return isKeyExist
}
}
// 实例化 PreferencesUtil 并导出单例
let preferenceUtilsObject : PreferencesUtil = new PreferencesUtil()
export default preferenceUtilsObject
(六) 其他页面的字号调整
除了设置“我的”页面的字体大小外,MainPage页面和Home组件中的字号也应根据设置进行适配,读者可自行尝试完善相应的实现。
二、知识点
用户首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。当用户希望有一个全局唯一存储的地方,可以采用用户首选项来进行存储。Preferences会将该数据缓存在内存中,当用户读取的时候,能够快速从内存中获取数据,当需要持久化时可以使用flush接口将内存中的数据写入持久化文件中。Preferences会随着存放的数据量越多而导致应用占用的内存越大,因此,Preferences不适合存放过多的数据,也不支持通过配置加密,适用的场景一般为应用保存用户的个性化设置(字体大小,是否开启夜间模式)等。
(一) 运作机制
如图所示,用户程序通过ArkTS接口调用用户首选项读写对应的数据文件。开发者可以将用户首选项持久化文件的内容加载到Preferences实例,每个文件唯一对应到一个Preferences实例,系统会通过静态容器将该实例存储在内存中,直到主动从内存中移除该实例或者删除该文件。
应用首选项的持久化文件保存在应用沙箱内部,可以通过context获取其路径。
(二) 约束限制
- 首选项无法保证进程并发安全,会有文件损坏和数据丢失的风险,不支持在多进程场景下使用。
- Key键为string类型,要求非空且长度不超过1024个字节。
- 如果Value值为string类型,请使用UTF-8编码格式,可以为空,不为空时长度不超过16MB。
- 当存储的数据中包含非UTF-8格式的字符串时,请使用Uint8Array类型存储,否则会造成持久化文件出现格式错误造成文件损坏。
- 当调用removePreferencesFromCache或者deletePreferences后,订阅的数据变更会主动取消订阅,重新getPreferences后需要重新订阅数据变更。
- 不允许deletePreferences与其他接口多线程、多进程并发调用,否则会发生不可预期行为。
- 内存会随着存储数据量的增大而增大,所以存储的数据量应该是轻量级的,建议存储的数据不超过一万条,否则会在内存方面产生较大的开销。
(三) 接口说明
以下是用户首选项持久化功能的相关接口。
| 接口名称 | 描述 |
|---|---|
| getPreferencesSync(context: Context, options: Options): Preferences | 获取Preferences实例。该接口存在异步接口。 |
| putSync(key: string, value: ValueType): void | 将数据写入Preferences实例,可通过flush将Preferences实例持久化。该接口存在异步接口。 |
| hasSync(key: string): boolean | 检查Preferences实例是否包含名为给定Key的存储键值对。给定的Key值不能为空。该接口存在异步接口。 |
| getSync(key: string, defValue: ValueType): ValueType | 获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue。该接口存在异步接口。 |
| deleteSync(key: string): void | 从Preferences实例中删除名为给定Key的存储键值对。该接口存在异步接口。 |
| flush(callback: AsyncCallback): void | 将当前Preferences实例的数据异步存储到用户首选项持久化文件中。 |
| on(type: 'change', callback: Callback): void | 订阅数据变更,订阅的数据发生变更后,在执行flush方法后,触发callback回调。 |
| off(type: 'change', callback?: Callback): void | 取消订阅数据变更。 |
| deletePreferences(context: Context, options: Options, callback: AsyncCallback): void | 从内存中移除指定的Preferences实例。若Preferences实例有对应的持久化文件,则同时删除其持久化文件。 |
(四) 开发步骤
- 导入@kit.ArkData模块。
import { preferences } from '@kit.ArkData'
2. 获取Preferences实例。
import { UIAbility } from '@kit.AbilityKit'
import { BusinessError } from '@kit.BasicServicesKit'
import { window } from '@kit.ArkUI'
let dataPreferences: preferences.Preferences | null = null
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
let options: preferences.Options = { name: 'myStore' }
dataPreferences = preferences.getPreferencesSync(this.context, options)
}
}
3. 写入数据。
使用putSync()方法保存数据到缓存的Preferences实例中。在写入数据后,如有需要,可使用flush()方法将Preferences实例的数据存储到持久化文件。示例代码如下所示:
import { util } from '@kit.ArkTS'
if (dataPreferences.hasSync('startup')) {
console.info("The key 'startup' is contained.")
} else {
console.info("The key 'startup' does not contain.")
// 此处以此键值对不存在时写入数据为例
dataPreferences.putSync('startup', 'auto')
// 当字符串有特殊字符时,需要将字符串转为Uint8Array类型再存储
let uInt8Array1 = new util.TextEncoder().encodeInto("~!@#¥%……&*()——+?")
dataPreferences.putSync('uInt8', uInt8Array1)
}
4. 读取数据。
使用getSync()方法获取数据,即指定键对应的值。如果值为null或者非默认值类型,则返回默认数据。
示例代码如下所示:
let val = dataPreferences.getSync('startup', 'default')
console.info("The 'startup' value is " + val)
// 当获取的值为带有特殊字符的字符串时,需要将获取到的Uint8Array转换为字符串
let uInt8Array2 : preferences.ValueType
= dataPreferences.getSync('uInt8', new Uint8Array(0))
let textDecoder = util.TextDecoder.create('utf-8')
val = textDecoder.decodeToString(uInt8Array2 as Uint8Array)
console.info("The 'uInt8' value is " + val)
5. 删除数据。
使用deleteSync()方法删除指定键值对,示例代码如下所示:
dataPreferences.deleteSync('startup')
6. 数据持久化。
应用存入数据到Preferences实例后,可以使用flush()方法实现数据持久化。示例代码如下所示:
dataPreferences.flush((err: BusinessError) => {
if (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`)
return
}
console.info('Succeeded in flushing.')
})
7. 订阅数据变更。
应用订阅数据变更需要指定observer作为回调方法。订阅的Key值发生变更后,当执行flush()方法时,observer被触发回调。示例代码如下所示:
let observer = (key: string) => {
console.info('The key' + key + 'changed.');
}
dataPreferences.on('change', observer);
// 数据产生变更,由'auto'变为'manual'
dataPreferences.put('startup', 'manual', (err: BusinessError) => {
if (err) {
console.error('Failed to put the value of 'startup'. '
+ `Code:${err.code},message:${err.message}`)
return
}
console.info("Succeeded in putting the value of 'startup'.")
if (dataPreferences !== null) {
dataPreferences.flush((err: BusinessError) => {
if (err) {
console.error('Failed to flush. '
+ `Code:${err.code}, message:${err.message}`)
return
}
console.info('Succeeded in flushing.')
})
}
})
8. 删除指定文件。
使用deletePreferences()方法从内存中移除指定文件对应的Preferences实例,包括内存中的数据。若该Preference存在对应的持久化文件,则同时删除该持久化文件,包括指定文件及其备份文件、损坏文件。
示例代码如下所示:
preferences.deletePreferences(this.context, options, (err: BusinessError) => {
if (err) {
console.error(`Failed to delete preferences. `
+ `Code:${err.code}, message:${err.message}`)
return
}
console.info('Succeeded in deleting preferences.')
})
✋ 需要参加鸿蒙认证的请点击 鸿蒙认证链接