1. 根据窗口获取断点值
export default class EntryAbility extends UIAbility {
private curBp: string = ''
// 其余略
onWindowStageCreate(windowStage: window.WindowStage): void {
windowStage.getMainWindow()
.then((windowObj) => {
// 获取应用启动时的窗口尺寸
this.updateBreakpoint(windowObj.getWindowProperties()
.windowRect
.width)
// 注册回调函数,监听窗口尺寸变化
windowObj.on('windowSizeChange', (windowSize) => {
this.updateBreakpoint(windowSize.width)
})
});
// 其余略
private updateBreakpoint(windowWidth: number): void {
// 将长度的单位由px换算为vp
let windowWidthVp = px2vp(windowWidth)
let newBp: string = ''
if (windowWidthVp < 320) {
newBp = BreakpointConstants.XS
} else if (windowWidthVp < 600) {
newBp = BreakpointConstants.SM
} else if (windowWidthVp < 840) {
newBp = BreakpointConstants.MD
} else {
newBp = BreakpointConstants.LG
}
if (this.curBp !== newBp) {
this.curBp = newBp
// 使用状态变量记录当前断点值
AppStorage.setOrCreate(BreakpointConstants.BREAK_POINT_KEY, this.curBp)
}
}
}
2. 通过 AppStorage 进行共享
3. 创建BreakPointType.ets
根据当前断点类型(如 xs, sm, md, lg)获取对应的值
flowchart TD
A[开始] --> B{当前断点类型是 xs?}
B -->|Yes| C[返回 xs 对应的值]
B -->|No| D{当前断点类型是 sm?}
D -->|Yes| E[返回 sm 对应的值]
D -->|No| F{当前断点类型是 md?}
F -->|Yes| G[返回 md 对应的值]
F -->|No| H{当前断点类型是 lg?}
H -->|Yes| I[返回 lg 对应的值]
H -->|No| J[返回 undefined]
declare interface BreakPointTypeOption<T> {
xs?: T
sm?: T
md?: T
lg?: T
}
export class BreakPointType<T> {
options: BreakPointTypeOption<T>
constructor(option: BreakPointTypeOption<T>) {
this.options = option
}
getValue(currentBreakPoint: string) {
if (currentBreakPoint === 'xs') {
return this.options.xs
} else if (currentBreakPoint === 'sm') {
return this.options.sm
} else if (currentBreakPoint === 'md') {
return this.options.md
} else if (currentBreakPoint === 'lg') {
return this.options.lg
} else {
return undefined
}
}
}
4. 导入,实例化工具对象,获取断点值
@StorageProp(BreakpointConstants.BREAK_POINT_KEY) breakPoint: string = 'xs'
5. 根据断点值,调整 tabs 的位置
flowchart TD
A[开始] --> B{判断断点类型}
B -->|sm 或 md| C[设置栏位位置为 End]
B -->|lg| D[设置栏位位置为 Start]
C --> E{判断断点类型}
D --> E
E -->|lg| F[设置布局为垂直]
E -->|其他| G[设置布局为水平]
F --> H[结束]
G --> H
@Entry
@Component
struct Index {
@StorageProp(BreakpointConstants.BREAK_POINT_KEY) breakPoint: string = 'xs'
build() {
Navigation(this.stackPath){
Tabs() {
}
.tabBar(this.TabItemBuilder(item, index))
}
.barPosition(new BreakPointType({
sm: BarPosition.End,
md: BarPosition.End,
lg: BarPosition.Start
}).getValue(this.breakPoint))
.vertical(this.breakPoint == 'lg' ? true : false)
.onTabBarClick(index => {
this.activeIndex = index
})
}
.hideTitleBar(true) // 隐藏标题栏
.mode(NavigationMode.Stack) // 设置单栏
.padding({bottom: this.bottomBarHeight})
}
}
效果展示
补充-常量抽取
export class BreakpointConstants {
// 手表等超小屏
static readonly XS: string = 'xs';
// 手机竖屏
static readonly SM: string = 'sm';
// 手机横屏,折叠屏
static readonly MD: string = 'md';
// 平板,2in1 设备
static readonly LG: string = 'lg';
// AppStorage 中的 key
static readonly BREAK_POINT_KEY: string = 'currentBreakpoint'
}