/** * ArkTS的滑動加載案例 */ // 自定義文章類 class Article { public id: number public title: string public content: string constructor(id:number, title:string, content:string) { this.id = id this.title = title this.content = content } } // 定義一篇文章展示的子組件 @Component struct ArticleComponent { article: Article build() { Row() { // Image('../../resources/base/media/icon.png') Image($r('app.media.icon')) .width(80) .height(80) .margin({right: 20}) Column() { Text(this.article.title) .fontSize(20) .margin({bottom: 8}) .fontColor(Color.Red) Text(this.article.content) .fontSize(16) .fontColor(Color.Brown) .margin({bottom: 8}) } .alignItems(HorizontalAlign.Start) .width('80%') .height('100%') } .padding(20) .borderRadius(12) // 圓角矩形 .backgroundColor('#FFECECEC') .height(80) .width('100%') .justifyContent(FlexAlign.SpaceBetween) } } @Entry @Component struct MyParent { // 是否導到列表的底部 @State isListReachEnd: boolean = false @State article_array: Array<Article> = [ // 初始化的時候,先創建幾篇文章 new Article(1, '第1篇文章', '精進自己,分享他人!'), new Article(2, '第2篇文章', '精進自己,分享他人!'), new Article(3, '第3篇文章', '精進自己,分享他人!'), new Article(4, '第4篇文章', '精進自己,分享他人!'), new Article(5, '第5篇文章', '精進自己,分享他人!'), new Article(6, '第6篇文章', '精進自己,分享他人!'), new Article(7, '第7篇文章', '精進自己,分享他人!'), new Article(8, '第8篇文章', '精進自己,分享他人!'), new Article(9, '第9篇文章', '精進自己,分享他人!') ] build() { Column() { List() { ForEach(this.article_array, (item: Article)=>{ ArticleComponent({article: item}) .margin({top:20}) }) }.onReachEnd(()=>{ // 到達列表的底部 this.isListReachEnd = true }) .parallelGesture(PanGesture({direction:PanDirection.Up, distance:80}) .onActionStart(()=>{ // 檢測到往上滑動的手勢 if (this.isListReachEnd) { // 加載新的文章 for (let index = 0; index < 3; index++) { // 一次加載3篇文章,循環可更改 let count = this.article_array.length let new_id = count + 1 this.article_array.push(new Article(new_id, '第'+new_id+'篇文章','精進自己,分享他人!')) this.isListReachEnd = false } } })) .padding(20) .scrollBar(BarState.Off) } .width('100%') .height('100%') } }