本文代码案例基于HarmonyOs NEXT,Api版本为12,DevEco Studio版本为5.0.3.900。
系统提供的List组件,是没有头部一说的,比如常见的使用场景如下:
@Entry
@Component
struct Index {
private mList: number[] = []
aboutToAppear(): void {
for (let i = 0; i < 20; i++) {
this.mList.push(i)
}
}
build() {
Column() {
List() {
ForEach(this.mList, (item: number) => {
ListItem() {
Text("条目" + item)
.width("100%")
.height(40)
.textAlign(TextAlign.Center)
.border({ width: { bottom: 1 }, color: Color.Gray })
}
})
}
.width("100%")
.height("100%")
.scrollBar(BarState.Off)
.edgeEffect(EdgeEffect.None)
}
}
}
从系统提供的方法中,我们是找不到任何可以添加头部的方法的,但是,在实际的开发中,列表上边增加头部信息,确实很常见的,毕竟某一个页面不单单是列表,有可能还有其他的组件,对于这种的实现方式,当然,我们也可以不使用头部,直接使用别的方式也能实现,但是,远没有添加头部实现起来方便。
第一个元素添加头组件
那么,如何给List组件添加头部组件呢,目前有两种实现方式,第一种就是给第一个条目上边添加头部组件,这种方式实现比较简单,代码如下:
@Entry
@Component
struct Index {
private mList: number[] = []
aboutToAppear(): void {
for (let i = 0; i < 20; i++) {
this.mList.push(i)
}
}
build() {
Column() {
List() {
ForEach(this.mList, (item: number, index: number) => {
ListItem() {
if (index == 0) {
Column() {
Column() {
Text("我是头组件")
}.width("100%")
.height(80)
.backgroundColor(Color.Red)
.justifyContent(FlexAlign.Center)
Text("条目" + item)
.width("100%")
.height(40)
.textAlign(TextAlign.Center)
.border({ width: { bottom: 1 }, color: Color.Gray })
}
} else {
Text("条目" + item)
.width("100%")
.height(40)
.textAlign(TextAlign.Center)
.border({ width: { bottom: 1 }, color: Color.Gray })
}
}
})
}
.width("100%")
.height("100%")
.scrollBar(BarState.Off)
.edgeEffect(EdgeEffect.None)
}
}
}
实际效果如下:
虽然上述的代码,能够实现给List组件添加头部组件,但是会存在一定的问题,那就是,如果列表没有数据怎么办?因为你是给第一个条目设置的头组件,目前列表中没有一个数据,那么显而易见,头组件也是不可能进行展示的,所以说这种给第一个元素设置头部的方法,仅仅适用于有数据的情况下。
Scroll组件嵌套实现头组件
第二种方式就是使用Scroll组件进行嵌套使用,也就是使用Scroll作为根组件,头组件在List组件之上,这里需要解决,List组件和Scroll组件之间的滑动冲突,这里使用的是nestedScroll。
.nestedScroll({
scrollForward: NestedScrollMode.PARENT_FIRST,
scrollBackward: NestedScrollMode.SELF_FIRST
})
全部代码
@Entry
@Component
struct Index {
private mList: number[] = []
aboutToAppear(): void {
for (let i = 0; i < 20; i++) {
this.mList.push(i)
}
}
build() {
Scroll() {
Column() {
Column() {
Text("我是头组件")
}.width("100%")
.height(80)
.backgroundColor(Color.Red)
.justifyContent(FlexAlign.Center)
List() {
ForEach(this.mList, (item: number, index: number) => {
ListItem() {
Text("条目" + item)
.width("100%")
.height(40)
.textAlign(TextAlign.Center)
.border({ width: { bottom: 1 }, color: Color.Gray })
}
})
}
.width("100%")
.height("100%")
.scrollBar(BarState.Off)
.edgeEffect(EdgeEffect.None)
.nestedScroll({
scrollForward: NestedScrollMode.PARENT_FIRST,
scrollBackward: NestedScrollMode.SELF_FIRST
})
}
}.width("100%")
.height("100%")
}
}
以上呢,就是两种方式实现头组件的方式,比较的简单,如果有下拉刷新操作的时候,需要特殊的处理。