当用户在聊天界面上滑时,通常需要从数据库中加载更早的消息,这些消息需要插入到当前消息列表的头部,如果直接将数据插入到头部而不进行其他操作,会使当前正在查看的消息被挤出屏幕。那么如何实现往List数据源数组的头部插入数据时List显示的项不变呢?
完整示例参考如下:
@Entry @Component struct StableList { @State listData: string[] = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10']; scrollerForList: Scroller = new Scroller(); @State ListIndex: number = 0; @State nextItemIndex: number = 0; build() { Column() { Row() { Button('头部插入数据') .onClick(() => this.prependItems()) .margin(10); Button('滚动到顶部') .onClick(() => this.scrollerForList.scrollToIndex(0)) .margin(10); }; List({ space: 20, initialIndex: this.ListIndex, scroller: this.scrollerForList }) { ForEach(this.listData, (item: string) => { ListItem() { Text(item) .fontSize(20) .width('100%') .textAlign(TextAlign.Center) .backgroundColor('#f5f5f5') .height(60); }; }, (item: string) => item); } .width('100%') .height('80%') .onScrollIndex((firstIndex: number) => { this.ListIndex = firstIndex; }); } .width('100%') .height('100%'); } prependItems() { console.info(`索引${this.ListIndex}`, ` 偏移量${this.scrollerForList.currentOffset().yOffset}`); const oldIndex: number = this.ListIndex; const newItems: string[] = []; for (let i = 0; i < 5; i++) { newItems.push(`new item${this.nextItemIndex + i}`); } this.nextItemIndex += 5; this.listData = [...newItems, ...this.listData]; // 计算新的位置并滚动 const newListLength: number = newItems.length; const newIndex: number = oldIndex + newListLength; this.scrollerForList.scrollToIndex(newIndex, false, undefined, { extraOffset: { value: this.scrollerForList.currentOffset().yOffset - 80 * oldIndex, unit: 1 } }); } }