@Entry
@Component
struct ListDemoOne {
@State message: number[] = [1, 2, 3];
@State num: number = 4;
build() {
Column() {
Stack() {
List() {
ForEach(this.message, (item: number) => {
ListItem() {
Column() {
Text(item.toString())
.textAlign(TextAlign.Center)
.backgroundColor('#F1F3F5')
.margin(3)
.borderRadius(12)
.width('70%')
.height(30);
}
.width('100%')
.justifyContent(FlexAlign.Center);
}
.width('100%')
.margin({ bottom: 5 })
.transition(TransitionEffect.translate({ y: 60 }));
}, (item: number) => item.toString());
}
.width('100%');
}
.alignContent(Alignment.BottomStart)
.layoutWeight(1);
Button('添加')
.margin({bottom:30})
.onClick(() => {
this.getUIContext().animateTo({
duration: 1000,
}, () => {
this.message.push(this.num);
this.num++;
});
});
}
.justifyContent(FlexAlign.Center)
.height('100%')
.width('100%')
.backgroundColor('#ffffffff');
}
} 在上述示例代码中,为List添加ListScroller,并在animateTo回调中调用this.listScroller.scrollEdge(Edge.Bottom),当插入项超出容器最大容量且列表高度超过屏幕时,新插入项的动画会触发,列表自动滚动至底部。完整示例参考如下:
@Entry
@Component
struct ListDemoTwo {
@State message: number[] = [1, 2, 3];
@State num: number = 4;
listcontroller: ListScroller = new ListScroller();
build() {
Column() {
Stack() {
List({ scroller: this.listcontroller }) {
ForEach(this.message, (item: number) => {
ListItem() {
Column() {
Text(item.toString())
.textAlign(TextAlign.Center)
.backgroundColor('#F1F3F5')
.margin(5)
.borderRadius(12)
.width('70%')
.height(30);
}
.justifyContent(FlexAlign.Center);
}
.width('100%')
.transition(TransitionEffect.translate({ y: 60 }));
}, (item: number) => item.toString());
}.width('100%');
}
.alignContent(Alignment.BottomStart)
.layoutWeight(1);
Button('添加')
.margin({bottom:20})
.onClick(() => {
this.getUIContext().animateTo({
duration: 1000,
}, () => {
this.message.push(this.num);
this.num++;
this.listcontroller.scrollEdge(Edge.Bottom);
});
});
}
.justifyContent(FlexAlign.End)
.height('100%')
.width('100%')
.backgroundColor('#ffffffff');
}
} 完整示例参考如下:
@Entry
@Component
struct ListDemoThree {
@State arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
private scroller: Scroller = new Scroller();
startIndex: number = 10;
build() {
Column() {
List({ space: 20, scroller: this.scroller }) {
ForEach(this.arr, (item: number) => {
ListItem() {
Text('' + item)
.width('100%')
.height(100)
.fontSize(16)
.textAlign(TextAlign.Center)
.borderRadius(20)
.backgroundColor('#F1F3F5');
}
.transition({ type: TransitionType.Delete, opacity: 0 });
}, (item: string) => item);
}.width('90%').scrollBar(BarState.Off);
Button('删除')
.width(100)
.onClick(() => {
this.getUIContext().animateTo({ duration: 500 }, () => {
if (this.arr.length > 0) {
this.arr.shift();
}
});
});
}.width('100%').height('90%').backgroundColor('white').padding({ top: 5 });
}
}