鸿蒙通用模块
一、常量部分
常量部分将项目中的样式与配置相关的数值统一抽离为独立的常量类,便于维护和全局复用,同时避免在代码中随意使用「魔数」。以下常量覆盖了响应式断点、百分比、字体粗细、间距、字号、圆角、图标尺寸、动画时长、透明度、层级、时间计算以及常用颜色等典型场景。所有常量均采用 static readonly 的方式定义,类型安全,取值一目了然。可根据自己项目实际情况进行拆分。
// 断点常量
export class BreakPointConstants {
// 手表等超小屏
static readonly XS: string = 'xs';
// 手机竖屏
static readonly SM: string = 'sm';
// 手机横屏,折叠屏
static readonly MD: string = 'md';
// 平板
static readonly LG: string = 'lg';
// PC
static readonly XL: string = 'xl';
}
// 百分比常量
export class PercentConstants {
static readonly FIVE_PERCENT: string = '5%'
static readonly TEN_PERCENT: string = '10%'
static readonly FIFTEEN_PERCENT: string = '15%'
static readonly TWENTY_PERCENT: string = '20%'
static readonly TWENTY_FIVE_PERCENT: string = '25%'
static readonly THIRTY_PERCENT: string = '30%'
static readonly THIRTY_FIVE_PERCENT: string = '35%'
static readonly FORTY_PERCENT: string = '40%'
static readonly FORTY_FIVE_PERCENT: string = '45%'
static readonly HALF_PERCENT: string = '50%'
static readonly FIFTY_FIVE_PERCENT: string = '55%'
static readonly SIXTY_PERCENT: string = '60%'
static readonly SIXTY_FIVE_PERCENT: string = '65%'
static readonly SEVENTY_PERCENT: string = '70%'
static readonly SEVENTY_FIVE_PERCENT: string = '75%'
static readonly EIGHTY_PERCENT: string = '80%'
static readonly EIGHTY_FIVE_PERCENT: string = '85%'
static readonly NINETY_PERCENT: string = '90%'
static readonly NINETY_FIVE_PERCENT: string = '95%'
static readonly FULL_PERCENT: string = '100%'
// 补充:常见非整十百分比
static readonly TWELVE_POINT_FIVE_PERCENT: string = '12.5%'
static readonly THIRTY_THREE_PERCENT: string = '33.33%'
static readonly SIXTY_SIX_PERCENT: string = '66.67%'
static readonly EIGHTY_SEVEN_POINT_FIVE_PERCENT: string = '87.5%'
}
// 字体粗细常量
export class FontWeightConstants {
static readonly FONT_WEIGHT_400: number = 400
static readonly FONT_WEIGHT_500: number = 500
static readonly FONT_WEIGHT_600: number = 600
static readonly FONT_WEIGHT_700: number = 700
}
// space间距常量
export class SpaceConstants {
static readonly SPACE_2: number = 2
static readonly SPACE_4: number = 4
static readonly SPACE_5: number = 5
static readonly SPACE_6: number = 6
static readonly SPACE_8: number = 8
static readonly SPACE_10: number = 10
static readonly SPACE_12: number = 12
static readonly SPACE_15: number = 15
static readonly SPACE_16: number = 16
static readonly SPACE_20: number = 20
static readonly SPACE_24: number = 24
static readonly SPACE_25: number = 25
static readonly SPACE_30: number = 30
static readonly SPACE_32: number = 32
static readonly SPACE_40: number = 40
static readonly SPACE_50: number = 50
static readonly SPACE_60: number = 60
static readonly SPACE_100: number = 100
}
// 字号常量(单位 fp)
export class FontSizeConstants {
static readonly FONT_SIZE_10: number = 10
static readonly FONT_SIZE_12: number = 12
static readonly FONT_SIZE_14: number = 14
static readonly FONT_SIZE_16: number = 16
static readonly FONT_SIZE_18: number = 18
static readonly FONT_SIZE_20: number = 20
static readonly FONT_SIZE_22: number = 22
static readonly FONT_SIZE_24: number = 24
static readonly FONT_SIZE_28: number = 28
static readonly FONT_SIZE_32: number = 32
static readonly FONT_SIZE_36: number = 36
static readonly FONT_SIZE_40: number = 40
static readonly FONT_SIZE_48: number = 48
}
// 圆角常量
export class RadiusConstants {
static readonly RADIUS_2: number = 2
static readonly RADIUS_4: number = 4
static readonly RADIUS_8: number = 8
static readonly RADIUS_12: number = 12
static readonly RADIUS_16: number = 16
static readonly RADIUS_20: number = 20
static readonly RADIUS_24: number = 24
static readonly RADIUS_32: number = 32
static readonly RADIUS_48: number = 48
// 胶囊/全圆角:传一个足够大的值即可实现
static readonly RADIUS_FULL: number = 1000
}
// 图标尺寸常量(单位 vp)
export class IconSizeConstants {
static readonly ICON_16: number = 16
static readonly ICON_18: number = 18
static readonly ICON_20: number = 20
static readonly ICON_24: number = 24
static readonly ICON_28: number = 28
static readonly ICON_32: number = 32
static readonly ICON_36: number = 36
static readonly ICON_40: number = 40
static readonly ICON_48: number = 48
}
// 动画时长常量(单位 ms)
export class DurationConstants {
static readonly DURATION_100: number = 100
static readonly DURATION_200: number = 200
static readonly DURATION_300: number = 300
static readonly DURATION_400: number = 400
static readonly DURATION_500: number = 500
static readonly DURATION_800: number = 800
static readonly DURATION_1000: number = 1000
static readonly DURATION_2000: number = 2000
// 默认动画时长
static readonly DEFAULT_DURATION: number = 1000
}
// 透明度常量
export class OpacityConstants {
static readonly OPACITY_0: number = 0
static readonly OPACITY_10: number = 0.1
static readonly OPACITY_20: number = 0.2
static readonly OPACITY_30: number = 0.3
static readonly OPACITY_40: number = 0.4
static readonly OPACITY_50: number = 0.5
static readonly OPACITY_60: number = 0.6
static readonly OPACITY_70: number = 0.7
static readonly OPACITY_80: number = 0.8
static readonly OPACITY_90: number = 0.9
static readonly OPACITY_100: number = 1
}
// 层级常量
export class ZIndexConstants {
static readonly Z_INDEX_1: number = 1
static readonly Z_INDEX_10: number = 10
static readonly Z_INDEX_100: number = 100
static readonly Z_INDEX_1000: number = 1000
}
// 时间常量(单位 ms)
export class TimeConstants {
static readonly SECOND: number = 1000
static readonly MINUTE: number = 60 * 1000
static readonly HOUR: number = 60 * 60 * 1000
static readonly DAY: number = 24 * 60 * 60 * 1000
static readonly WEEK: number = 7 * 24 * 60 * 60 * 1000
}
// 常用颜色常量
export class CommonColorConstants {
static readonly TRANSPARENT: string = '#00000000'
static readonly WHITE: string = '#FFFFFF'
static readonly BLACK: string = '#000000'
static readonly GRAY: string = '#999999'
static readonly LIGHT_GRAY: string = '#F1F3F5'
static readonly MASK: string = '#33000000'
static readonly RED: string = '#E84026'
static readonly GREEN: string = '#1AA86E'
static readonly BLUE: string = '#0A59F7'
static readonly ORANGE: string = '#FF8F1F'
}
二、常用工具函数
1、断点管理工具(一多开发)
该工具是一个专为“一多开发”(一次开发、多端部署)场景设计的响应式取值工具类。它接受不同断点(xs、sm、md、lg、xl)对应的配置值,并根据当前的屏幕宽度断点自动返回匹配的结果。典型用法是将不同屏幕尺寸下的样式值(如间距、字号、列数等)封装进 BreakpointType 实例,一行代码即可按断点取到适配的值,省去大量 if-else 或 switch 判断。
export interface BreakpointTypes<T> {
xs?: T
sm: T
md: T
lg: T
xl?: T
}
export class BreakpointType<T> {
private xs: T
private sm: T
private md: T
private lg: T
private xl: T
public constructor(param: BreakpointTypes<T>) {
this.xs = param.xs ?? param.sm
this.sm = param.sm
this.md = param.md
this.lg = param.lg
this.xl = param.xl ?? param.lg
}
public getValue(currentBreakpoint: WidthBreakpoint): T {
if (currentBreakpoint === WidthBreakpoint.WIDTH_XS) {
return this.xs
}
if (currentBreakpoint === WidthBreakpoint.WIDTH_SM) {
return this.sm
}
if (currentBreakpoint === WidthBreakpoint.WIDTH_MD) {
return this.md
}
if (currentBreakpoint === WidthBreakpoint.WIDTH_XL) {
return this.xl
}
return this.lg
}
}
项目中使用示例:
Text("测试文字")
.fontSize(new BreakPointType({
xs: 10,
sm: 12,
md: 14,
lg: 16,
xl: 18
}).getValue(this.currentBreakpoint))
2、Preferences(首选项)
该工具是对鸿蒙中首选项的轻量封装,以单例模式对外提供统一的键值对存取服务。它在内部维护一个全局的 Preferences 实例,并提供 getData、putData 和 removeData 三个核心静态方法,覆盖首选项数据的读取、写入和删除场景。相比直接调用原生 API,这套封装简化了调用方对实例生命周期和异常处理的管理。
import { preferences, ValueType } from '@kit.ArkData';
import { Context } from '@kit.AbilityKit';
export class PrefStore {
static pref: preferences.Preferences | null = null
/**
获取实例
*/
public static getPreference(context: Context) {
if (!PrefStore.pref) {
try {
PrefStore.pref = preferences.getPreferencesSync(context, { name: "key" });
}
catch (error) {
console.error("获取实例失败:" + error)
}
}
}
/**
获取数据
@param key 键
@param value 默认值
*/
public static getData(context: Context, key: string, value: ValueType) {
if (!PrefStore.pref) {
PrefStore.getPreference(context)
}
if (!PrefStore.pref) {
return value
}
try {
return PrefStore.pref.getSync(key, value)
}
catch (error) {
console.error("获取数据失败:" + error)
return value
}
}
/**
存储数据
@param key 键
@param value 值
*/
public static putData(context: Context, key: string, value: ValueType) {
if (!PrefStore.pref) {
PrefStore.getPreference(context)
}
if (!PrefStore.pref) {
return
}
try {
PrefStore.pref.putSync(key, value)
PrefStore.pref.flushSync()
}
catch (error) {
console.error("存储数据失败:" + error)
}
}
/**
删除数据
@param key 键
*/
public static removeData(context: Context, key: string) {
if (!PrefStore.pref) {
PrefStore.getPreference(context)
}
if (!PrefStore.pref) {
return
}
try {
PrefStore.pref.deleteSync(key)
PrefStore.pref.flushSync()
}
catch (error) {
console.error("删除数据失败:" + error)
}
}
}
3、日志工具
该日志工具对鸿蒙原生日志 API 进行了轻量封装,提供了一套统一的日志输出方案。它支持 DEBUG、INFO、WARN、ERROR 四个日志级别,通过修改 Logger.level 即可一键切换全局日志输出策略:开发期设为 DEBUG 全量打印,上线前改为 ERROR 只保留错误日志,生产环境可直接设为 OFF 完全关闭。此外,工具还支持自动从调用栈中解析日志的触发位置(文件名和行号),方便快速定位问题代码。
// 日志级别
export enum LogLevel {
DEBUG = 0,
INFO = 1,
WARN = 2,
ERROR = 3,
OFF = 4,
}
export class Logger {
// ★★★ 一键开关:只改这一行,全局生效 ★★★
// LogLevel.DEBUG → 全量打印(开发期)
// LogLevel.ERROR → 只留错误(上线前改这个)
// LogLevel.OFF → 全关(一个日志都不打)
private static level: LogLevel = LogLevel.DEBUG;
// 是否在日志里附带调用位置(文件:行号),开发期定位用;发布前可改为 false 省一点性能
private static showLine: boolean = true;
// 全局日志标签
private static tag: string = '[Snooker]';
// 从调用栈解析"业务代码在哪个文件哪一行调用了 Logger"
private static getCaller(): string {
if (!Logger.showLine) {
return '';
}
try {
const stack = new Error().stack;
if (!stack) {
return '';
}
const lines = stack.split('\n');
// 不固定行号:跳过 Logger 工具自身的帧,取第一个业务代码帧
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.includes('Logger.ets') || line.includes('getCaller')) {
continue;
}
const match = line.match(/(?:\(|\s)([\/\w.\-]+\.ets):(\d+):(\d+)\)?/);
if (match) {
const fileName = match[1].substring(match[1].lastIndexOf('/') + 1);
return `[${fileName}:${match[2]}]`;
}
}
}
catch (e) {
// 解析失败就当作没有行号,不影响日志本身
}
return '';
}
public static debug(...args: Object[]): void {
if (Logger.level <= LogLevel.DEBUG) {
console.debug(Logger.tag, Logger.getCaller(), ...args);
}
}
public static info(...args: Object[]): void {
if (Logger.level <= LogLevel.INFO) {
console.info(Logger.tag, Logger.getCaller(), ...args);
}
}
public static warn(...args: Object[]): void {
if (Logger.level <= LogLevel.WARN) {
console.warn(Logger.tag, Logger.getCaller(), ...args);
}
}
public static error(...args: Object[]): void {
if (Logger.level <= LogLevel.ERROR) {
console.error(Logger.tag, Logger.getCaller(), ...args);
}
}
}更多推荐


所有评论(0)