在实现适老化功能时,有以下经典场景:
import dataPreferences from '@ohos.data.preferences';
let preferences: dataPreferences.Preferences | null = null;
let options: dataPreferences.Options = { name: 'myStore' };
@Entry
@Component
struct AgeFriendly {
// 获取当前组件的上下文(用于访问数据存储等系统服务)
context: Context | undefined = this.getUIContext().getHostContext();
@State isOn: boolean = false;
@State customSize: string = '18vp';
// 生命周期钩子:在组件即将显示前执行(通常用于初始化数据)
aboutToAppear(): void {
preferences = dataPreferences.getPreferencesSync(this.context, options);
if (!preferences) {
return;
}
// 从本地存储中读取 'customSize' 的值,若不存在则使用默认值 '18vp'
let customSize = preferences.getSync('customSize', '18vp');
let isOn = preferences.getSync('isOn', 'false');
console.info('The size value is' + customSize + '| isOn: ' + isOn);
this.isOn = JSON.parse(isOn as string);
this.customSize = customSize.toString();
}
build() {
Column() {
Text('点击按钮切换长者模式')
.fontSize(this.customSize)
.fontColor(Color.Black);
Row() {
// Toggle 开关控件:用于开启/关闭长者模式
Toggle({
type: ToggleType.Switch, // type: Switch 表示显示为滑动开关样式
isOn: this.isOn // isOn: 绑定响应式状态变量,开关状态实时同步
})
.selectedColor('#007DFF')
.switchPointColor('#FFFFFF')
.onChange((isOn: boolean) => {
// 当开关状态改变时触发的回调函数
this.isOn = isOn; // 更新本地状态变量
this.customSize = isOn ? '28vp' : '18vp'; // 根据状态切换字体大小
if (!preferences) {
return;
}
// 根据开关状态写入新的字体大小值
if (isOn) {
preferences.putSync('customSize', '28vp');
preferences.putSync('isOn', 'true');
} else {
preferences.putSync('customSize', '18vp');
preferences.putSync('isOn', 'false');
}
// 强制将所有未写入的数据立即刷新到磁盘(确保持久化生效)
preferences.flush();
});
};
}
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
.width('100%')
.height('100%');
}
}