线性布局
通过线性容器[Row]和[Column]构建
Column容器内子元素按照垂直方向排列,Row容器内子元素按照水平方向排列
1、Column容器
内部的元素–垂直排列
@Entry
@Component
struct ViewA {
build() {
// Column({ space: 20 }) {
// Column().width('80%').height('25%').backgroundColor(0x88DEB3)
// Column().width('80%').height('25%').backgroundColor(0xD2888C)
// Column().width('80%').height('25%').backgroundColor(0xF5DE88)
// }.width('100%')
Column({ space: 20 }) {
Row().width('80%').height('25%').backgroundColor(0x88DEB3)
Row().width('80%').height('25%').backgroundColor(0xD2888C)
Row().width('80%').height('25%').backgroundColor(0xF5DE88)
}.width('100%')
}
}
这两段代码呈现效果相同
总结:
Column({ space: 20 }) { 。。。}.width(‘100%’)
只要是Column容器,内部的元素就呈现垂直排列,无论内部是Column或是Row
space: 20 内部元素间隔20
width(‘100%’) 最外层宽度占100%
2、Row容器
内部的元素–水平排列
Row({ space: 35 }) {
Row().width('20%').height(150).backgroundColor(0x88DEB3)
Row().width('20%').height(150).backgroundColor(0xD2888C)
Row().width('20%').height(150).backgroundColor(0xF5DE88)
}.width('90%')
在这里插入图片描述
Row每给定高度,默认内容自适应
Row({ space: 35 }) {
Row().width('20%').height(150).backgroundColor(0x88DEB3)
Row().width('20%').height(150).backgroundColor(0xD2888C)
Row().width('20%').height(150).backgroundColor(0xF5DE88)
}.width('90%').height("100%")
// Row({ space: 35 }) {
// Column().width('20%').height(150).backgroundColor(0x88DEB3)
// Column().width('20%').height(150).backgroundColor(0xD2888C)
// Column().width('20%').height(150).backgroundColor(0xF5DE88)
// }.width('90%').height("100%")
这两段代码呈现效果相同:
指定高度,默认居中
只要是Row容器,内部的元素就呈现水平排列,无论内部是Column或是Row
3、对齐方式
Column({}) {}.width(‘100%’).alignItems(HorizontalAlign.Start)
对齐方式参数:alignItems(HorizontalAlign.Start)
Column({}) {
Column() {
}.width('80%').height(50).backgroundColor(0xF5DEB3)
Column() {
}.width('80%').height(50).backgroundColor(0xD2B48C)
Column() {
}.width('80%').height(50).backgroundColor(0xF5DEB3)
}.width('100%').alignItems(HorizontalAlign.Start).backgroundColor('rgb(242,242,242)')
Row({。。}) {}.width(‘100%’).alignItems(VerticalAlign.Top)
Column({}) {}…justifyContent(FlexAlign.Start)
Row({}) {}…justifyContent(FlexAlign.Start)
4、自适应处理
线性布局用空白填充组件Blank在容器主轴方向自动填充空白空间,达到自适应拉伸效果
没用Blank情况:
加Blank情况:
5、案例
多数据滚动条线性布局应用
完整代码:
@Entry
@Component
struct ViewA {
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) => {
Row(){
Text(item.toString())
.width('70%')
.height(90)
.backgroundColor(0x887a55)
.borderRadius(15)
.fontSize(16)
.textAlign(TextAlign.Center)
.margin({ top: 10 })
Button('确定', { type: ButtonType.Circle, stateEffect: false })
.backgroundColor(0x317a88)
.width(90)
.height(90)
}.width('100%')
}, item => item)
}.width('100%')
}
.backgroundColor(0xDCDCDC)
.scrollable(ScrollDirection.Vertical) // 滚动方向为垂直方向
.scrollBar(BarState.On) // 滚动条常驻显示
.scrollBarColor(Color.Yellow) // 滚动条颜色
.scrollBarWidth(10) // 滚动条宽度
.edgeEffect(EdgeEffect.Spring) // 滚动到边沿后回弹
}
}
以上内容参考“官方文档”