img

一、案例介绍

本案例将展示Marquee组件的基础用法,通过实现一个新闻公告栏来演示文本滚动效果的基本实现方法。我们将学习如何控制文本滚动的方向、速度,以及如何处理滚动事件。

二、实现效果

  • 实现基础的文本滚动效果
  • 支持暂停和继续滚动
  • 可控制滚动方向
  • 展示滚动状态和事件处理

三、代码实现

1. 基础结构搭建

@Component
struct MarqueeBasicDemo {
  @State private isScrolling: boolean = true
  @State private scrollDirection: MarqueeDirection = MarqueeDirection.Left
  private newsContent: string = '今日要闻:HarmonyOS NEXT发布会召开,带来多项重要更新。开发者大会公布多项重磅消息,生态建设进入新阶段。'

  build() {
    Column({ space: 20 }) {
      // 标题区域
      Text('新闻公告栏')
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .margin({ top: 20 })

      // 跑马灯展示区域
      this.MarqueeDisplay()

      // 控制按钮区域
      this.ControlButtons()
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#F1F3F5')
    .padding(16)
  }
}

2. 跑马灯展示区域实现

@Component
struct MarqueeBasicDemo {
  // ... 前面的代码保持不变

  @Builder
  MarqueeDisplay() {
    Row() {
      Marquee({
        start: this.isScrolling,
        step: 6,
        loop: true,
        direction: this.scrollDirection,
        onStart: () => this.handleMarqueeStart(),
        onFinish: () => this.handleMarqueeFinish()
      }) {
        Text(this.newsContent)
          .fontSize(16)
          .fontColor('#182431')
      }
      .width('90%')
      .height(40)
      .backgroundColor('#FFFFFF')
      .borderRadius(8)
      .padding({ left: 12, right: 12 })
    }
    .width('100%')
    .justifyContent(FlexAlign.Center)
  }

  private handleMarqueeStart() {
    console.info('跑马灯开始滚动')
  }

  private handleMarqueeFinish() {
    console.info('跑马灯完成一次滚动')
  }
}

3. 控制按钮区域实现

@Component
struct MarqueeBasicDemo {
  // ... 前面的代码保持不变

  @Builder
  ControlButtons() {
    Column({ space: 16 }) {
      // 滚动控制按钮
      Row({ space: 20 }) {
        Button(this.isScrolling ? '暂停' : '开始')
          .onClick(() => {
            this.isScrolling = !this.isScrolling
          })
          .width(100)
          .backgroundColor(this.isScrolling ? '#FF0000' : '#007DFF')

        Button('切换方向')
          .onClick(() => {
            this.scrollDirection = this.scrollDirection === MarqueeDirection.Left ?
              MarqueeDirection.Right : MarqueeDirection.Left
          })
          .width(100)
          .backgroundColor('#36D1DC')
      }

      // 状态显示
      Row() {
        Text(`当前状态:${this.isScrolling ? '滚动中' : '已暂停'}`)
          .fontSize(14)
          .fontColor('#666666')
      }
      .margin({ top: 8 })

      // 方向显示
      Row() {
        Text(`滚动方向:${this.scrollDirection === MarqueeDirection.Left ? '向左' : '向右'}`)
          .fontSize(14)
          .fontColor('#666666')
      }
    }
    .margin({ top: 20 })
  }
}

四、总结

通过本案例,我们学到了:

  1. Marquee组件的基础用法和配置
  2. 如何控制文本滚动的状态和方向
  3. 事件处理和状态管理的实现方法
  4. 界面布局和样式优化技巧

掌握这些基础知识后,我们就可以在实际项目中灵活运用Marquee组件,实现各种文本滚动效果。在后续案例中,我们将探索更多高级用法和实际应用场景。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐