HarmonyOS/OpenHarmony应用开发-ArkTS自适应线性布局自适应延伸实现
自适应延伸是在不同尺寸设备下,当页面显示内容个数不一并延伸到屏幕外时,可通过滚动条拖动展示。适用于线性布局中内容无法一屏展示的场景。常见以下两类实现方法。
一、List组件
List子项过多一屏放不下时,未展示的子项通过滚动条拖动显示。通过scrollBar属性设置滚动条的常驻状态,edgeEffect属性设置拖动到极限的回弹效果。
纵向List:
@Entry @Component struct ListExample1 { @State arr: string[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"] @State alignListItem: ListItemAlign = ListItemAlign.Start build() { Column() { List({ space: 20, initialIndex: 0 }) { ForEach(this.arr, (item) => { ListItem() {Text('' + item) .width('100%') .height(100) .fontSize(16) .textAlign(TextAlign.Center) .borderRadius(10) .backgroundColor(0xFFFFFF) } .border({ width: 2, color: Color.Green }) }, item => item) } .border({ width: 2, color: Color.Red, style: BorderStyle.Dashed }) .scrollBar(BarState.On) // 滚动条常驻 .edgeEffect(EdgeEffect.Spring) // 滚动到边缘再拖动回弹效果 }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding(20) } }
横向List
@Entry @Component struct ListExample2 { @State arr: string[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"] @State alignListItem: ListItemAlign = ListItemAlign.Start build() { Column() { List({ space: 20, initialIndex: 0 }) { ForEach(this.arr, (item) => { ListItem() {Text('' + item) .height('100%') .width(100) .fontSize(16) .textAlign(TextAlign.Center) .borderRadius(10) .backgroundColor(0xFFFFFF) } .border({ width: 2, color: Color.Green }) }, item => item) } .border({ width: 2, color: Color.Red, style: BorderStyle.Dashed }) .scrollBar(BarState.On) // 滚动条常驻 .edgeEffect(EdgeEffect.Spring) // 滚动到边缘再拖动回弹效果 .listDirection(Axis.Horizontal) // 列表水平排列 }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding(20) } }
二、Scroll组件
线性布局中,当子组件的布局尺寸超过父组件的尺寸时,内容可以滚动。在Column或者Row外层包裹一个可滚动的容器组件Scroll实现。
纵向Scroll:
@Entry@Componentstruct ScrollExample { scroller: Scroller = new Scroller(); private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; build() { Scroll(this.scroller) { Column() { ForEach(this.arr, (item) => { Text(item.toString()) .width('90%') .height(150) .backgroundColor(0xFFFFFF) .borderRadius(15) .fontSize(16) .textAlign(TextAlign.Center) .margin({ top: 10 }) }, item => item) }.width('100%') } .backgroundColor(0xDCDCDC) .scrollable(ScrollDirection.Vertical) // 滚动方向纵向 .scrollBar(BarState.On) // 滚动条常驻显示 .scrollBarColor(Color.Gray) // 滚动条颜色 .scrollBarWidth(30) // 滚动条宽度 .edgeEffect(EdgeEffect.Spring) // 滚动到边沿后回弹 }}
复制
横向Scroll:
参考引用自官方文档。