鸿蒙掌上驾考宝典应用开发28:通用应用设置组件——app_setting 多端适配
·
第28篇:通用应用设置组件——app_setting 多端适配

一、引言
应用设置是每个应用都需要的通用功能,包括字体大小、深色模式、关于页面、隐私协议等。DriverLicenseExam 项目的 app_setting 组件封装了这些通用设置功能,并支持折叠屏、平板、手机的多端适配。
二、组件结构
2.1 目录结构
app_setting/
├── src/main/ets/
│ ├── common/ ← 工具类
│ │ ├── FontUtils.ets ← 字体工具
│ │ ├── CustomModifier.ets ← 自定义修饰
│ │ └── GridRowColSetting.ets ← 网格布局设置
│ ├── components/ ← UI 组件
│ │ ├── SettingCard.ets ← 设置项卡片
│ │ ├── FontSizeSlider.ets ← 字体大小滑块
│ │ └── NavHeaderBar.ets ← 导航头
│ ├── models/ ← 数据模型
│ │ ├── BreakpointModel.ets ← 断点模型
│ │ ├── FontModel.ets ← 字体模型
│ │ └── WindowModel.ets ← 窗口模型
│ ├── pages/ ← 设置页面
│ │ ├── SettingFont.ets ← 字体设置
│ │ ├── SettingAbout.ets ← 关于页面
│ │ └── SettingPrivacy.ets ← 隐私设置
│ └── views/SettingView.ets ← 设置主视图
三、字体大小设置
3.1 字体缩放实现
// FontUtils.ets
export class FontUtils {
// 设置字体缩放比例
static setFontScale(scale: number) {
// 应用字体缩放
}
// 获取当前字体缩放
static getFontScale(): number {
return 1.0; // 默认比例
}
}
3.2 字体大小滑块
// FontSizeSlider.ets
@ComponentV2
export struct FontSizeSlider {
@Local fontSize: number = 1.0;
build() {
Column() {
Text('字体大小')
.fontSize(16);
Slider({
value: this.fontSize,
min: 0.85,
max: 1.15,
step: 0.05,
})
.onChange((value: number) => {
this.fontSize = value;
FontUtils.setFontScale(value);
});
Row() {
Text('小').fontSize(12);
Blank();
Text('大').fontSize(12);
}
}
}
}
四、深色模式设置
4.1 主题选项
// LightDarkOptions.ets
export const LIGHT_DARK_OPTIONS = [
{ label: '跟随系统', value: 0 },
{ label: '浅色模式', value: 1 },
{ label: '深色模式', value: 2 },
];
4.2 设置交互
// 设置页面中的深色模式选择
SettingSelectDialog({
options: LIGHT_DARK_OPTIONS,
selectedValue: this.currentMode,
onSelect: (value: number) => {
this.currentMode = value;
AppStorage.setOrCreate('lightDarkMode', value);
// 应用主题
context.getApplicationContext().setColorMode(
value === 0 ? ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET :
value === 1 ? ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT :
ConfigurationConstant.ColorMode.COLOR_MODE_DARK
);
},
});
五、多端适配
5.1 断点模型
// BreakpointModel.ets
export class BreakpointModel {
// 根据屏幕宽度返回断点
static getBreakpoint(width: number): string {
if (width < 520) return 'sm'; // 手机
if (width < 840) return 'md'; // 折叠屏展开
return 'lg'; // 平板
}
}
5.2 响应式布局
// GridRowColSetting.ets
build() {
GridRow() {
GridCol({ span: { sm: 12, md: 8, lg: 6 } }) {
// 设置内容
}
}
}
六、总结
通用应用设置组件封装了字体、深色模式、关于页面、隐私协议等设置功能,并通过断点模型实现了多端适配,提供了统一的设置体验。
关键源码文件:
components/app_setting/src/main/ets/views/SettingView.etscomponents/app_setting/src/main/ets/pages/SettingFont.etscomponents/app_setting/src/main/ets/models/BreakpointModel.etscomponents/app_setting/src/main/ets/common/FontUtils.ets
更多推荐

所有评论(0)