HarmonyOS6 ArkTS Grid 设置自适应列数

张开发
2026/4/7 5:38:01 15 分钟阅读

分享文章

HarmonyOS6 ArkTS Grid 设置自适应列数
文章目录原理与前提1. 核心语法2. 生效前提完整代码三种自适应模式详解1. auto-fill固定列宽自动填充列数核心逻辑语法2. auto-fit固定最小列宽铺满容器核心逻辑语法适用场景3. auto-stretch固定列宽剩余空间分配给间距核心逻辑语法三种模式核心差异对比总结原理与前提1. 核心语法Grid自适应列数依赖columnsTemplate的高级语法格式为.columnsTemplate(repeat(自适应关键字, 列宽值))repeat()重复布局函数简化重复列定义。自适应关键字auto-fill、auto-fit、auto-stretch决定空间分配逻辑。列宽值固定列宽如70默认单位 vp仅支持单个值auto-stretch不支持百分比。2. 生效前提无需设置rowsTemplate仅通过columnsTemplate定义自适应规则Grid会自动计算行数以容纳所有子项。完整代码EntryComponentstruct GridColumnsTemplateDemo{itemsA:number[][0,1,2,3,4,5];itemsB:number[][0,1,2,3,4,5];itemsC:number[][0,1,2,3,4,5];build(){Column({space:12}){Text(auto-fill根据固定列宽自动填充列数).width(90%).fontSize(15)Grid(){ForEach(this.itemsA,(item:number){GridItem(){Text(Item${item}).height(85).textAlign(TextAlign.Center)}.backgroundColor(0xFF9800)})}.width(90%).border({width:1,color:Color.Grey}).columnsTemplate(repeat(auto-fill, 70)).columnsGap(10).rowsGap(10).height(155)Text(auto-fit自动铺满宽度剩余空间均分至每列).width(90%).fontSize(15)Grid(){ForEach(this.itemsB,(item:number){GridItem(){Text(Item${item}).height(85).textAlign(TextAlign.Center)}.backgroundColor(0xFF5722)})}.width(90%).border({width:1,color:Color.Grey}).columnsTemplate(repeat(auto-fit, 70)).columnsGap(10).rowsGap(10).height(155)Text(auto-stretch剩余空间全部分配给列间距).width(90%).fontSize(15)Grid(){ForEach(this.itemsC,(item:number){GridItem(){Text(Item${item}).height(85).textAlign(TextAlign.Center)}.backgroundColor(0x4CAF50)})}.width(90%).border({width:1,color:Color.Grey}).columnsTemplate(repeat(auto-stretch, 70)).columnsGap(10).rowsGap(10).height(155)}.width(100%).height(100%).padding({top:10})}}运行效果如图三种自适应模式详解1. auto-fill固定列宽自动填充列数核心逻辑以固定列宽计算可容纳的最大列数容器剩余空间不分配保留空白区域。语法.columnsTemplate(repeat(auto-fill, 70))2. auto-fit固定最小列宽铺满容器核心逻辑先按固定列宽计算列数再将容器剩余空间均分到每一列让网格铺满容器宽度无空白。语法.columnsTemplate(repeat(auto-fit, 70))适用场景需要铺满容器、视觉整齐的场景如商品列表、卡片流。3. auto-stretch固定列宽剩余空间分配给间距核心逻辑以固定列宽计算列数容器剩余空间全部分配给列间距columnsGap列宽保持固定间距自动拉伸。语法.columnsTemplate(repeat(auto-stretch, 70))三种模式核心差异对比模式列宽变化剩余空间分配视觉效果适用场景auto-fill固定70vp保留空白右侧可能有空白固定尺寸子项、严格布局auto-fit拉伸70vp均分到每一列铺满容器、无空白商品列表、卡片流、响应式布局auto-stretch固定70vp均分到列间距列宽固定、间距变大导航菜单、分类标签、固定图标总结auto-stretch列宽不支持百分比仅支持px/vp/纯数字。三种模式均需配合ForEach/LazyForEach渲染子项适配数据驱动布局。多端适配时优先使用auto-fit兼顾列数与容器铺满效果。Grid自适应列数通过columnsTemplate的repeat()与三种关键字实现了灵活的响应式布局auto-fill固定列宽保留空白auto-fit拉伸列宽铺满容器auto-stretch固定列宽拉伸间距。如果这篇文章对你有帮助欢迎点赞、收藏、关注你的支持是持续创作的动力

更多文章