[鸿蒙2025领航者闯关] Scroll滑动容器与布局优化技巧

问题描述

在长列表或复杂页面中,如何正确使用 Scroll 组件?如何处理 Scroll 嵌套问题?如何实现流畅的滑动效果和弹性边界?

关键字: Scroll、滑动容器、嵌套滑动、edgeEffect、布局优化

解决方案

完整代码

复制代码
@Entry
@Component
struct ScrollDemo {
  @State records: string[] = Array.from({ length: 50 }, (_, i) => `记录 ${i + 1}`);
  private scroller: Scroller = new Scroller();
  
  build() {
    Column() {
      // 顶部固定区域
      this.buildHeader()
      
      // 可滚动内容区域
      Scroll(this.scroller) {
        Column({ space: 12 }) {
          // 统计卡片
          this.buildStatsCard()
          
          // 筛选器
          this.buildFilters()
          
          // 记录列表
          this.buildRecordList()
        }
        .width('100%')
        .padding(16)
      }
      .width('100%')
      .layoutWeight(1)
      .scrollable(ScrollDirection.Vertical) // 垂直滚动
      .scrollBar(BarState.Auto) // 自动显示滚动条
      .scrollBarColor('#888') // 滚动条颜色
      .scrollBarWidth(4) // 滚动条宽度
      .edgeEffect(EdgeEffect.Spring) // 弹性边界效果
      .friction(0.6) // 摩擦系数(越小滑动越远)
      .onScroll((xOffset: number, yOffset: number) => {
        // 滚动监听
        console.log(`滚动偏移: ${yOffset}`);
      })
      .onScrollEdge((side: Edge) => {
        // 滚动到边界
        console.log(`滚动到边界: ${side}`);
      })
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#f5f5f5')
  }
  
  @Builder
  buildHeader() {
    Row() {
      Text('记录列表')
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
      
      Blank()
      
      Button('回到顶部')
        .fontSize(14)
        .onClick(() => {
          // 滚动到顶部
          this.scroller.scrollEdge(Edge.Top);
        })
    }
    .width('100%')
    .padding(16)
    .backgroundColor(Color.White)
  }
  
  @Builder
  buildStatsCard() {
    Row({ space: 12 }) {
      Column() {
        Text('500')
          .fontSize(24)
          .fontWeight(FontWeight.Bold)
          .fontColor('#ff6b6b')
        Text('总收入')
          .fontSize(12)
          .fontColor('#999')
      }
      .layoutWeight(1)
      .padding(16)
      .backgroundColor(Color.White)
      .borderRadius(12)
      
      Column() {
        Text('300')
          .fontSize(24)
          .fontWeight(FontWeight.Bold)
          .fontColor('#67c23a')
        Text('总支出')
          .fontSize(12)
          .fontColor('#999')
      }
      .layoutWeight(1)
      .padding(16)
      .backgroundColor(Color.White)
      .borderRadius(12)
    }
    .width('100%')
  }
  
  @Builder
  buildFilters() {
    Row({ space: 8 }) {
      Text('全部').filterChip(true)
      Text('收入').filterChip(false)
      Text('支出').filterChip(false)
    }
    .width('100%')
  }
  
  @Builder
  buildRecordList() {
    Column({ space: 8 }) {
      ForEach(this.records, (record: string) => {
        Row() {
          Text(record)
            .fontSize(16)
        }
        .width('100%')
        .padding(16)
        .backgroundColor(Color.White)
        .borderRadius(8)
      })
    }
    .width('100%')
  }
}
​
// 扩展方法:筛选标签样式
@Extend(Text)
function filterChip(selected: boolean) {
  .fontSize(14)
  .padding({ left: 16, right: 16, top: 8, bottom: 8 })
  .backgroundColor(selected ? '#ff6b6b' : '#f5f5f5')
  .fontColor(selected ? Color.White : '#333')
  .borderRadius(16)
}
​
/**
 * Scroll嵌套解决方案
 */
@Component
struct NestedScrollDemo {
  private outerScroller: Scroller = new Scroller();
  private innerScroller: Scroller = new Scroller();
  
  build() {
    // 外层Scroll
    Scroll(this.outerScroller) {
      Column({ space: 16 }) {
        // 固定内容
        Text('外层内容')
          .width('100%')
          .height(200)
          .backgroundColor('#e3f2fd')
        
        // 内层Scroll(横向)
        Scroll(this.innerScroller) {
          Row({ space: 12 }) {
            ForEach([1, 2, 3, 4, 5], (item: number) => {
              Text(`卡片${item}`)
                .width(150)
                .height(100)
                .backgroundColor('#fff3e0')
                .textAlign(TextAlign.Center)
                .borderRadius(8)
            })
          }
          .padding(16)
        }
        .width('100%')
        .scrollable(ScrollDirection.Horizontal) // 横向滚动
        .scrollBar(BarState.Off) // 隐藏滚动条
        
        // 更多固定内容
        Text('更多外层内容')
          .width('100%')
          .height(400)
          .backgroundColor('#f3e5f5')
      }
      .width('100%')
    }
    .width('100%')
    .height('100%')
    .scrollable(ScrollDirection.Vertical) // 纵向滚动
  }
}
​
/**
 * Scroller控制器高级用法
 */
@Component
struct ScrollerControlDemo {
  private scroller: Scroller = new Scroller();
  @State currentOffset: number = 0;
  
  build() {
    Column() {
      // 控制按钮
      Row({ space: 8 }) {
        Button('滚动到顶部')
          .onClick(() => {
            this.scroller.scrollEdge(Edge.Top);
          })
        
        Button('滚动到底部')
          .onClick(() => {
            this.scroller.scrollEdge(Edge.Bottom);
          })
        
        Button('滚动到指定位置')
          .onClick(() => {
            // 滚动到500px位置,动画时长300ms
            this.scroller.scrollTo({
              xOffset: 0,
              yOffset: 500,
              animation: {
                duration: 300,
                curve: Curve.EaseInOut
              }
            });
          })
        
        Button('滚动一页')
          .onClick(() => {
            // 向下滚动一页
            this.scroller.scrollPage({
              next: true,
              direction: Axis.Vertical
            });
          })
      }
      .padding(16)
      
      Text(`当前偏移: ${this.currentOffset.toFixed(0)}px`)
        .padding(8)
      
      // 滚动内容
      Scroll(this.scroller) {
        Column({ space: 12 }) {
          ForEach(Array.from({ length: 30 }, (_, i) => i), (index: number) => {
            Text(`内容 ${index + 1}`)
              .width('100%')
              .height(80)
              .backgroundColor('#e0f7fa')
              .textAlign(TextAlign.Center)
              .borderRadius(8)
          })
        }
        .padding(16)
      }
      .layoutWeight(1)
      .onScroll((xOffset: number, yOffset: number) => {
        this.currentOffset += yOffset;
      })
    }
    .width('100%')
    .height('100%')
  }
}

原理解析

1. Scroll 基本属性

复制代码
.scrollable(ScrollDirection.Vertical) // 滚动方向
.scrollBar(BarState.Auto) // 滚动条显示策略
.edgeEffect(EdgeEffect.Spring) // 边界效果
.friction(0.6) // 摩擦系数

2. Scroller 控制器

复制代码
scroller.scrollEdge(Edge.Top) // 滚动到边界
scroller.scrollTo({ yOffset: 500 }) // 滚动到指定位置
scroller.scrollPage({ next: true }) // 翻页

3. 嵌套滑动

  • 外层 Scroll:纵向滚动
  • 内层 Scroll:横向滚动
  • 不同方向不冲突

4. 滚动监听

复制代码
.onScroll((xOffset, yOffset) => {
  // 滚动偏移量
})
.onScrollEdge((side: Edge) => {
  // 滚动到边界
})

最佳实践

  1. 固定头部: 头部放在 Scroll 外面,避免滚动
  2. layoutWeight: Scroll 使用 layoutWeight(1)填充剩余空间
  3. 边界效果: 使用 EdgeEffect.Spring 提升体验
  4. 滚动条: 长列表显示滚动条,短内容隐藏
  5. 性能优化: 内容过多时使用 List+LazyForEach

避坑指南

  1. 嵌套方向: 嵌套 Scroll 必须方向不同
  2. height 设置: Scroll 必须有明确高度
  3. Column 嵌套: Scroll 内 Column 不要设置 height
  4. 滚动冲突: 同方向嵌套会导致滚动冲突
  5. 内存占用: 内容过多时 Scroll 会全部渲染,考虑用 List

效果展示

  • 弹性边界:滚动到顶部/底部时有弹性效果
  • 流畅滑动:摩擦系数 0.6,滑动流畅自然
  • 精确控制:通过 Scroller 实现各种滚动效果
    相关资源
相关推荐
waeng_luo2 小时前
[鸿蒙2025领航者闯关] 响应式布局与屏幕适配方案
华为·harmonyos·鸿蒙2025领航者闯关·鸿蒙6实战·开发者年度总结
waeng_luo3 小时前
[鸿蒙2025领航者闯关] 表单验证与用户输入处理最佳实践
开发语言·前端·鸿蒙·鸿蒙2025领航者闯关·鸿蒙6实战·开发者年度总结
kirk_wang5 小时前
Flutter Image Editor 适配鸿蒙HarmonyOS平台实践
flutter·华为·harmonyos
国霄7 小时前
(7)Kotlin/Js For Harmony——ArkTs 开发架构
harmonyos
kirk_wang7 小时前
Flutter三方库鸿蒙适配实战:从原理到落地
flutter·移动开发·跨平台·arkts·鸿蒙
盐焗西兰花7 小时前
鸿蒙学习实战之路:Dialog 组件封装最佳实践
学习·华为·harmonyos
大雷神7 小时前
HarmonyOS中高德地图第一篇:高德地图SDK集成与初始化
harmonyos
大雷神7 小时前
HarmonyOS中开发高德地图第五篇:定位蓝点功能
harmonyos
汉堡黄•᷄ࡇ•᷅8 小时前
鸿蒙开发:案例集合List:ListItem拖拽(交换位置,过渡动画)(性能篇)
华为·harmonyos·鸿蒙·鸿蒙系统