大屏适配
介绍
框架内置断点状态与响应式工具,支持列表、网格、文本、尺寸等多种适配方式。断点由 WindowAdapter 监听窗口宽度并写入全局状态,页面按断点动态调整布局即可。
断点类型与规则
断点规则位于 core/state/src/main/ets/BreakpointState.ets,当前默认规则如下:
| 断点 | 说明 | 最大宽度(vp) |
|---|---|---|
XS | 超小屏 | 320 |
SM | 小屏 | 600 |
MD | 中屏 | 840 |
LG | 大屏 | Infinity |
断点效果说明:
- XS:超小屏(< 320vp)
- SM:小屏(< 600vp)
- MD:中屏(< 840vp)
- LG:大屏(>= 840vp)
示例一:网格布局适配
ScreenAdaptDemoPage 中按断点调整列数:
- 小屏(SM):2 列
- 中屏(MD):3 列
- 大屏(LG):4 列
ts
import { bp } from "state";
/**
* @file 网格布局适配示例
*/
@Builder
private GridSection(): void {
Grid() {
// ... 省略数据循环
}
.columnsTemplate(bp({ sm: "1fr 1fr", md: "1fr 1fr 1fr", lg: "1fr 1fr 1fr 1fr" }))
.width("100%");
}示例二:列表布局适配
小屏一列,大屏两列:
ts
import { bp } from "state";
/**
* @file 列表布局适配示例
*/
@Builder
private ListSection(): void {
Grid() {
// ... 省略数据循环
}
.columnsTemplate(bp({ sm: "1fr", md: "1fr 1fr", lg: "1fr 1fr" }))
.width("100%");
}示例三:文本适配
根据断点调整字号:
ts
import { bp } from "state";
/**
* @file 文本适配示例
*/
@Builder
private TextAdaptSection(): void {
Text("大屏适配示例文字")
.fontSize(bp({ sm: 16, md: 20, lg: 28 }));
}示例四:控件尺寸适配
根据断点返回不同尺寸值:
ts
import { bp } from "state";
/**
* @file 尺寸适配示例
*/
private getSizeValue(): string {
return bp({ sm: "80vp", md: "96vp", lg: "120vp" });
}示例五:Tab 栏大屏位置调整
在 MainPage 中,底部 Tab 栏在大屏横屏时切换到左侧:
ts
import { BreakpointState, getBreakpointState } from "state";
/**
* @file 主页面视图
*/
@ComponentV2
export struct MainPage {
/**
* 屏幕断点状态
*/
@Local
private breakpointState: BreakpointState = getBreakpointState();
/**
* 主页面内容视图
* @returns {void} 无返回值
*/
@Builder
private MainContent(): void {
Tabs({
barPosition: this.breakpointState.isLG() ? BarPosition.Start : BarPosition.End,
}) {
// ... 省略页面内容
}
.barWidth(this.breakpointState.isLG() ? 96 : "100%")
.vertical(this.breakpointState.isLG());
}
}API 说明
文件位置:core/state/src/main/ets/BreakpointState.ets
BreakpointState 属性
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
current | 当前断点类型 | BreakpointType | SM |
windowWidthVp | 当前窗口宽度(vp) | number | 0 |
BreakpointState 方法
| 方法 | 说明 | 参数 | 返回值 |
|---|---|---|---|
updateByWidth | 根据宽度刷新断点 | windowWidthVp: number | void |
resolveBreakpoint | 计算断点类型 | windowWidthVp: number | BreakpointType |
isXS / isSM / isMD / isLG | 是否为对应断点 | - | boolean |
getValue | 根据断点返回适配值 | options: BreakpointValueOptions<T>defaultValue?: T | T |
全局函数
| 方法 | 说明 | 参数 | 返回值 |
|---|---|---|---|
getBreakpointState | 获取全局断点状态 | - | BreakpointState |
bp | 获取断点适配值 | options: BreakpointValueOptions<T>defaultValue?: T | T |
使用建议
- 优先使用
bp()做断点值映射,避免硬编码。 - 列表/网格布局建议统一使用
Grid搭配断点列数。 - 大屏横屏场景优先考虑导航或操作栏位置调整。