鸿蒙 轮播显示Swiper组件

本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新

一、Swiper 概述

Swiper 是鸿蒙系统提供的滑块视图容器组件,用于实现子组件的滑动轮播显示功能。它支持以下主要特性:

  1. 水平或垂直方向滑动:通过 vertical 属性控制方向。
  2. 自动轮播与循环播放:设置 autoPlay 和 loop 属性。
  3. 导航点指示器:支持圆点和数字样式。
  4. 动画与性能优化:支持自定义动画曲线和预加载功能。
  5. 手势与编程控制:用户手势滑动或通过 SwiperController 编程控制。

二、核心 API

1. 基础配置属性

属性类型描述
loopboolean是否开启循环播放模式,默认值 true
autoPlayboolean是否启用自动轮播,默认值 false
intervalnumber自动轮播的时间间隔(单位:毫秒),默认值 3000
verticalboolean是否为纵向滑动,默认值 false(横向滑动)。
width / heightnumber / string设置 Swiper 的宽度和高度,支持固定值或百分比。

2. 导航点指示器

属性类型描述
indicatorDotIndicator / DigitIndicator / boolean设置导航点指示器样式。支持圆点和数字样式。
indicatorConfig{ itemWidth, itemHeight, color, selectedColor, bottom }定制导航点的样式和位置。

示例:自定义导航点样式

Swiper()
  .indicator(new DotIndicator())
  .indicatorConfig({
    itemWidth: 8,          // 圆点宽度
    itemHeight: 8,         // 圆点高度
    color: '#999999',      // 未选中颜色
    selectedColor: '#007DFF', // 选中颜色
    bottom: 16,            // 距底部16vp
    align: IndicatorAlign.Center // 水平居中
  })

3. 动画与性能优化

属性类型描述
durationnumber页面切换的动画时长(单位:毫秒),默认值 400
curveCurve / string设置动画曲线,支持 LinearEaseInEaseOut 等标准曲线。
cachedCountnumber预加载前后页面的个数,默认值 1,用于提升性能。
disableSwipeboolean是否禁用手势滑动,默认值 false

4. 编程控制

通过 SwiperController 实现对轮播图的编程控制。

方法描述
showPrevious()切换到上一页。
showNext()切换到下一页。
showIndex(index)跳转到指定索引页(从 0 开始)。
refresh()刷新轮播内容,用于动态更新数据。

5. 其他高级属性

属性类型描述
indexnumber设置当前显示的子组件索引,默认值 0
itemSpacenumber / string子组件之间的间隙,默认值 0,不支持百分比。
displayModeSwiperDisplayMode设置子组件显示模式,默认值 Stretch(拉伸充满)。
effectModestring切换效果模式,支持 spring(弹簧效果)和 fade(渐隐渐显)。

三、使用示例

示例 1:基础轮播图

@Entry
@Component
struct BasicSwiperExample {
  build() {
    Swiper() {
      Text("页面1")
        .width('100%')
        .height('100%')
        .backgroundColor(Color.Red)
        .textAlign(TextAlign.Center)
        .fontSize(30)

      Text("页面2")
        .width('100%')
        .height('100%')
        .backgroundColor(Color.Green)
        .textAlign(TextAlign.Center)
        .fontSize(30)

      Text("页面3")
        .width('100%')
        .height('100%')
        .backgroundColor(Color.Blue)
        .textAlign(TextAlign.Center)
        .fontSize(30)
    }
    .height(200)
    .loop(true)  // 循环播放
    .autoPlay(true)  // 自动轮播
    .interval(3000)  // 3秒间隔
    .indicator(true)  // 显示导航点
  }
}

示例 2:图片轮播器

@Entry
@Component
struct ImageSwiperExample {
  private imageList: string[] = [
    '/common/image1.jpg',
    '/common/image2.jpg',
    '/common/image3.jpg'
  ]
  
  build() {
    Swiper() {
      ForEach(this.imageList, (item: string) => {
        Image(item)
          .width('100%')
          .height(200)
          .objectFit(ImageFit.Cover)
      })
    }
    .width('100%')
    .height(200)
    .loop(true)
    .autoPlay(true)
    .interval(3000)
    .indicator(new DotIndicator())
    .indicatorConfig({
      color: '#999999',
      selectedColor: '#007DFF',
      bottom: 16
    })
  }
}

示例 3:编程控制轮播

@Entry
@Component
struct SwiperControlExample {
  private controller: SwiperController = new SwiperController();
  private currentIndex: number = 0;
  
  build() {
    Column() {
      Swiper(this.controller) {
        ForEach([1, 2, 3], (page: number) => {
          Text(`页面 ${page}`)
            .width('100%')
            .height(200)
            .backgroundColor(page % 2 === 0 ? Color.Gray : Color.White)
        })
      }
      .height(200)
      .width('100%')
      .onChange((index: number) => {
        this.currentIndex = index;
      })

      Row() {
        Button('上一页')
          .onClick(() => this.controller.showPrevious())
        Button('下一页')
          .onClick(() => this.controller.showNext())
        Button(`跳转到第3页`)
          .onClick(() => this.controller.showIndex(2))
      }
    }
  }
}

四、高级用法

1. 动态数据更新

通过 @State 实现数据动态刷新:

@State banners: Resource[] = [$r('app.media.banner1'), $r('app.media.banner2')];
private controller: SwiperController = new SwiperController();

// 更新数据
updateBanners() {
  this.banners = [$r('app.media.newBanner1'), $r('app.media.newBanner2'), $r('app.media.newBanner3')];
  this.controller.refresh();  // 刷新轮播内容
}

2. 自定义指示器

通过 ForEach 实现自定义导航点:

Row() {
  ForEach(this.swiperData, (item: string, index: number) => {
    Circle()
      .width(index === this.currentIndex ? 12 : 8)
      .height(8)
      .fill(index === this.currentIndex ? '#007DFF' : '#999999')
      .margin(4)
  })
}
.margin({ top: 12 })
.justifyContent(FlexAlign.Center)

鸿蒙Swiper组件华为自研的UI组件库中用于实现轮播效果的部分,它支持多种内容展示,包括图片和HTML5视频。如果你想在轮播视频时设置视频自动播放,可以按照以下步骤操作: 1. **引入Swiper和Video组件**:首先,确保已经导入了`HarmonyOS.SwipeableView`(Swiper)和`HarmonyOS.VideoPlayer`组件。 ```java import com.huawei.hms.ui.appwidgets.SwipeableView; import com.huawei.hms.ui.appwidgets.video.widget.VideoPlayer; ``` 2. **初始化Swiper组件**:在你的视图中创建并初始化Swiper实例,并配置包含VideoPlayer的卡片项。 ```java SwipeableView swiper = new SwipeableView(this); swiper.setPages(Arrays.asList( new ViewPage<>(new VideoPlayer(this, R.raw.your_video_url)), // 其他页面... )); ``` 这里`R.raw.your_video_url`应替换为你的实际视频资源路径。 3. **设置自动播放属性**:在VideoPlayer对象中,你可以调用`setAutoPlay(true)`方法来开启视频的自动播放功能。 ```java VideoPlayer videoPlayer = (VideoPlayer) swiper.getPages().get(0).getView(); videoPlayer.setAutoPlay(true); ``` 4. **处理滑动切换**:当用户通过Swiper切换到下一个或前一个页面时,需要暂停当前正在播放的视频,并开始新的视频(如果设置了自动播放的话)。 ```java swiper.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(int position, View view) { if (position > 0) { // 检查是否是第一个页面 videoPlayer.onPause(); // 停止当前播放 videoPlayer = (VideoPlayer) swiper.getPages().get(position).getView(); videoPlayer.start(); // 开始新视频播放 } } }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值