#鸿蒙通关秘籍##鸿蒙通关秘籍#如何在HarmonyOS NEXT中实现类似知乎日报的首页轮播图效?

HarmonyOS
2024-11-29 13:47:18
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
NAT梦幻绘师

在HarmonyOS NEXT中实现类似知乎日报的首页轮播图效果,可以使用Swiper组件来展示图片,并在轮播图的底部添加标题。可以通过Stack组件将文本标题叠加到轮播图之上,实现半透明背景效果,以提高视觉美感和可读性。以下是实现此功能的完整代码:

import { getSwiperList } from "../../common/api/home"
import { BaseResponse, ErrorResp } from '../../common/bean/ApiTypes';
import { Log } from '../../utils/logutil'

class MySwiperData implements IDataSource {
  private list: number[] = []

  constructor(list: number[]) {
    this.list = list
  }

  totalCount(): number {
    return this.list.length
  }

  getData(index: number): number {
    return this.list[index]
  }

  registerDataChangeListener(listener: DataChangeListener): void {
  }

  unregisterDataChangeListener() {
  }
}

@Component
export default struct ZhiHu {
  @State message: string = 'Hello World';
  private swiperController: SwiperController = new SwiperController()
  private data: MySwiperData = new MySwiperData([])

  aboutToAppear() {
    Log.info('ZhiHu aboutToAppear');
    getSwiperList().then((res) => {
      Log.debug(res.data.message)
    }).catch((err: BaseResponse<ErrorResp>) => {
      Log.debug("request", "error", err.data.message)
    });
    let list: number[] = [];
    for (let i = 1; i <= 10; i++) {
      list.push(i);
    }
    this.data = new MySwiperData(list);
  }

  aboutToDisappear() {
    Log.info('ZhiHu aboutToDisappear');
  }

  build() {
    Row() {
      Column({ space: 0 }) {
        Text("日报")
          .size({ width: '100%', height: 50 })
          .backgroundColor("#28bff1")
          .fontColor("#ffffff")
          .textAlign(TextAlign.Center)
          .fontSize("18fp");

        Stack({ alignContent: Alignment.Center }) {
          Swiper(this.swiperController) {
            LazyForEach(this.data, (item: string) => {
              Text(item.toString())
                .width('100%')
                .height(160)
                .backgroundColor(0xAFEEEE)
                .textAlign(TextAlign.Center)
                .fontSize(30);
            }, (item: string) => item);
          }
          .autoPlay(true)
          .interval(4000)
          .loop(true)
          .duration(1000)
          .zIndex(1);

          Text("标题")
            .margin({ top: 80 })
            .width('100%').height(50)
            .textAlign(TextAlign.Center)
            .fontSize(20)
            .fontColor(Color.White)
            .opacity(100)
            .backgroundColor('#808080AA')
            .zIndex(2);
        }.height(160);
      }.size({ width: '100%', height: '100%' });
    }
  }
}
分享
微博
QQ
微信
回复
2024-11-29 16:00:45
相关问题