鸿蒙 ark ui 轮播图实现教程

news2024/9/24 1:23:29

前言:

各位同学有段时间没有见面 因为一直很忙所以就没有去更新博客。最近有在学习这个鸿蒙的ark ui开发 因为鸿蒙不是发布了一个鸿蒙next的测试版本 明年会启动纯血鸿蒙应用 所以我就想提前给大家写一些博客文章

效果图

具体实现

我们在鸿蒙的ark ui 里面列表使用我们的Swiper组件来实现 我们的轮播图

准备数据源

import { PictureItem } from '../bean/PictureItem';

/**
 * Pictures of banner.
 */
export const PICTURE_BANNER: PictureItem[] = [
  { 'id': '1', 'name': '怒海', 'description': '怒海波涛', 'image': $r('app.media.image1') },
  { 'id': '2', 'name': '大山深处', 'description': '大山深处感人的亲情之歌', 'image': $r('app.media.image2') },
  { 'id': '3', 'name': '荒漠', 'description': '荒漠的亲情之歌', 'image': $r('app.media.image3') }
];

/**
 * type of pictures.
 */
export enum PictureType {
  BANNER = 'banner',
}

Bean类


/**
 * Picture entity class.
 */
export class PictureItem {
  id: string;
  name: string;
  description: string;
  image: Resource;

  constructor(id: string, name: string, description: string, image: Resource) {
    this.id = id;
    this.name = name;
    this.description = description;
    this.image = image;
  }
}

宽高常量配置


/**
 * Common constants for all features.
 */
export class CommonConstants {

  /**
   * animation duration of tab content switching.
   */
  static readonly DURATION_ADS = 200;


  /**
   * height of carousel title.
   */
  static readonly HEIGHT_CAROUSEL_TITLE = 90;

  /**
   * fontSize of description.
   */
  static readonly FONT_SIZE_DESCRIPTION = 12;
  /**
   * font size of title.
   */
  static readonly FONT_SIZE_TITLE = 20;

  static readonly FONT_WEIGHT_LIGHT = 400;
  /**
   * bold font.
   */
  static readonly FONT_WEIGHT_BOLD = 700;

  /**
   * page layout weight.
   */
  static readonly LAYOUT_WEIGHT = 1;

  /**
   * border angle.
   */
  static readonly BORDER_RADIUS = 12;

  /**
   * line height for more.
   */
  static readonly LINE_HEIGHT_MORE = 19;
  /**
   * rolling duration.
   */
  static readonly SWIPER_TIME = 1500;
  /**
   * margin of text bottom.
   */
  static readonly BOTTOM_TEXT = 4;

  /**
   * margin of banner top.
   */
  static readonly TOP_ADS = 12;
  /**
   * margin of banner left.
   */
  static readonly ADS_LEFT = 12;

  /*
   * maximum width.
   */
  static readonly FULL_WIDTH = '100%';
  /**
   * maximum height.
   */
  static readonly FULL_HEIGHT = '100%';
  /**
   * width of tab page.
   */
  static readonly PAGE_WIDTH = '100%';
  /**
   * height of banner.
   */
  static readonly HEIGHT_BANNER = '27%';

 
}

具体布局


import router from '@ohos.router';
import { PictureItem } from '../bean/PictureItem';
import { PictureType } from '../constants/PictureConstants';
import { initializePictures, startPlay, stopPlay } from './PictureViewModel';
import { CommonConstants } from '../constants/CommonConstant';



@Extend(Text) function textStyle(fontSize: number, fontWeight: number) {
  .fontSize(fontSize)
  .fontColor($r('app.color.start_window_background'))
  .fontWeight(fontWeight)
}

/**
 * Carousel banner.
 */
@Component
export struct Banner {
  @State index: number = 0;
  private imageArray: Array<PictureItem> = [];
  private swiperController: SwiperController = new SwiperController();

  aboutToAppear() {
    // Data Initialization.
    this.imageArray = initializePictures(PictureType.BANNER);
    // Turn on scheduled task.
    startPlay(this.swiperController);
  }

  aboutToDisappear() {
    stopPlay();
  }

  build() {
    Swiper(this.swiperController) {
      ForEach(this.imageArray, item => {
        Stack({ alignContent: Alignment.TopStart }) {
          Image(item.image)
            .objectFit(ImageFit.Fill)
            .height(CommonConstants.FULL_HEIGHT)
            .width(CommonConstants.FULL_WIDTH)
            .borderRadius(CommonConstants.BORDER_RADIUS)
            .align(Alignment.Center)
            .onClick(() => {
             console.log("点击事件 item"+item.id)
            })

          Column() {
            Text($r('app.string.movie_classic'))
              .textStyle(CommonConstants.FONT_SIZE_DESCRIPTION, CommonConstants.FONT_WEIGHT_LIGHT)
              .margin({ bottom: CommonConstants.BOTTOM_TEXT })
            Text(item.name)
              .textStyle(CommonConstants.FONT_SIZE_TITLE, CommonConstants.FONT_WEIGHT_BOLD)
          }
          .alignItems(HorizontalAlign.Start)
          .height(CommonConstants.HEIGHT_CAROUSEL_TITLE)
          .margin({ top: CommonConstants.TOP_ADS, left: CommonConstants.ADS_LEFT })
        }
        .height(CommonConstants.FULL_HEIGHT)
        .width(CommonConstants.FULL_WIDTH)
      }, item => JSON.stringify(item))
    }
    .width(CommonConstants.PAGE_WIDTH)
    .height(CommonConstants.HEIGHT_BANNER)
    .index(this.index)
    .indicatorStyle({ selectedColor: $r('app.color.start_window_background') })
    .indicator(true)
    .duration(CommonConstants.DURATION_ADS)
  }
}

使用 indicator 属性设置是否支持自动轮播

.indicator(true)

设置自动轮播间隔时间

.duration(CommonConstants.DURATION_ADS)

viewmodel 实现

import { PictureItem } from '../bean/PictureItem';
import { PICTURE_BANNER} from '../constants/PictureConstants';
import { PictureType } from '../constants/PictureConstants';
import { CommonConstants } from '../constants/CommonConstant';

/**
 * Initialize picture data according to type.
 *
 * @param initType Init type.
 */
export function initializePictures(initType: string): Array<PictureItem> {
  let imageDataArray: Array<PictureItem> = [];
  switch (initType) {
    case PictureType.BANNER:
      PICTURE_BANNER.forEach((item) => {
        imageDataArray.push(new PictureItem(item.id, item.name, item.description, item.image));
      })
      break;
    default:
      break;
  }
  return imageDataArray;
}

let timerIds: number[] = [];

/**
 * start scheduled task.
 *
 * @param swiperController Controller.
 */
export function startPlay(swiperController: SwiperController) {
  let timerId = setInterval(() => {
    swiperController.showNext();
  }, CommonConstants.SWIPER_TIME);
  timerIds.push(timerId);
}

/**
 * stop scheduled task.
 */
export function stopPlay() {
  timerIds.forEach((item) => {
    clearTimeout(item);
  })
}

最后总结:

arkui 写法和flutter非常的像 有兴趣的同学可以多尝试哈 今天的文章就讲到这里 。最后呢 希望我都文章能帮助到各位同学工作和学习

为了能让大家更好的学习鸿蒙 (Harmony OS) 开发技术,这边特意整理了《鸿蒙 (Harmony OS)开发学习手册》(共计890页),希望对大家有所帮助:https://qr21.cn/FV7h05

《鸿蒙 (Harmony OS)开发学习手册》

入门必看

  1. 应用开发导读(ArkTS)
  2. 应用开发导读(Java)

HarmonyOS 概念:https://qr21.cn/FV7h05

  1. 系统定义
  2. 技术架构
  3. 技术特性
  4. 系统安全

如何快速入门

  1. 基本概念
  2. 构建第一个ArkTS应用
  3. 构建第一个JS应用
  4. ……

开发基础知识:https://qr21.cn/FV7h05

  1. 应用基础知识
  2. 配置文件
  3. 应用数据管理
  4. 应用安全管理
  5. 应用隐私保护
  6. 三方应用调用管控机制
  7. 资源分类与访问
  8. 学习ArkTS语言
  9. ……

基于ArkTS 开发:https://qr21.cn/FV7h05

  1. Ability开发
  2. UI开发
  3. 公共事件与通知
  4. 窗口管理
  5. 媒体
  6. 安全
  7. 网络与链接
  8. 电话服务
  9. 数据管理
  10. 后台任务(Background Task)管理
  11. 设备管理
  12. 设备使用信息统计
  13. DFX
  14. 国际化开发
  15. 折叠屏系列
  16. ……

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1244239.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【jvm】虚拟机之堆

目录 一、堆的核心概述二、堆的内存细分&#xff08;按分代收集理论设计&#xff09;2.1 java7及以前2.2 java8及以后 三、堆内存大小3.1 说明3.2 参数设置3.3 默认大小3.4 手动设置3.5 jps3.6 jstat3.7 OutOfMemory举例 四、年轻代与老年代4.1 说明 五、对象分配过程5.1 说明5…

开源Flutter on Desktop项目-极扩安卓开发者工具

极扩-安卓开发者工具 他能干嘛 这个Flutter on Desktop桌面项目可以辅助你开发APP&#xff0c;支持分析一些运行数据以及操作APK安装等功能&#xff0c;甚至我还加入了Window安卓子系统的功能。 在它的帮助下&#xff0c;你可以快速查看当前正在运行的Activity&#xff0c;给你…

OpenCV实现图像噪声、去噪基本方法

一、噪声分类 1、高斯噪声 指服从高斯分布&#xff08;正态分布&#xff09;的一类噪声&#xff0c;其产生的主要原因是由于相机在拍摄时视场较暗且亮度不均匀造成的&#xff0c;同时相机长时间工作使得温度过高也会引起高斯噪声&#xff0c;另外电路元器件白身噪声和互相影响…

简单聊聊加密和加签的关系与区别

大家好&#xff0c;我是G探险者。 平时我们在项目上一定都听过加密和加签&#xff0c;加密可能都好理解&#xff0c;知道它是保障的数据的机密性&#xff0c;那加签是为了保障啥勒&#xff1f;它和加密有啥区别&#xff1f; 带着这个疑问&#xff0c;我们就来聊聊二者的区别。…

【Python】Fastapi swagger-ui.css 、swagger-ui-bundle.js 无法加载,docs无法加载,redocs无法使用

使用fastapi的时候&#xff0c;swagger-ui.css 、swagger-ui-bundle.js、redoc.standalone.js 有时候无法加载&#xff08;国内环境原因或者是局域网屏蔽&#xff09;&#xff0c;此时就需要自己用魔法下载好对应文件&#xff0c;然后替换到fastapi里面去。 fastapi里面依靠这…

redis运维(十九)redis 的扩展应用 lua(一)

一 redis 的扩展应用 lua redis如何保证原子操作 说明&#xff1a;引入lua脚本,核心解决原子性问题 ① redis为什么引入lua? lua脚本本身体积小,启动速度快 ② redis引入lua的优势 小结&#xff1a; 类似自定义redis命令 ③ redis中如何使用lua ④ EVAL 说明&#…

《算法通关村——数论问题解析》

《算法通关村——数论问题解析》 辗转相除法 辗转相除法又叫做欧几里得算法,是公元前 300 年左右的希腊数学家欧几里得在他的著作《几何原本》提出的。最大公约数(greatest common divisor&#xff0c;简写为gcd&#xff09;&#xff0c;是指几个数的共有的因数之中最大的一个…

csv文件添加文件内容和读取

append content to file import numpy as np acc_listnp.array([0.97,0.92,0.93,0.89]) # 注意这个地方添加文件不需要特别声明是什么文件 file open("result.csv", "a") print("{:.2f}, {:.2f}".format(acc_list.mean(), acc_list.std()), f…

leetcode刷题日志-167.两数之和II-输入有序数组

给你一个下标从 1 开始的整数数组 numbers &#xff0c;该数组已按 非递减顺序排列 &#xff0c;请你从数组中找出满足相加之和等于目标数 target 的两个数。如果设这两个数分别是 numbers[index1] 和 numbers[index2] &#xff0c;则 1 < index1 < index2 < numbers.…

浏览器没收到返回,后端也没报错,php的json_encode问题bug

今天网站遇到个问题&#xff0c;后端返回异常&#xff0c;但是浏览器状态码200&#xff0c;但是看不到结果。经过排查发现&#xff0c;我们在返回结果的时候使用了json_encode返回给前端&#xff0c;结果里面的字符编码异常&#xff0c;导致json_encode异常&#xff0c;但是php…

ComfyUI搭建使用教程

ComfyUI 是一个基于节点流程式的stable diffusion AI 绘图工具WebUI&#xff0c; 你可以把它想象成集成了stable diffusion功能的substance designer&#xff0c; 通过将stable diffusion的流程拆分成节点&#xff0c;实现了更加精准的工作流定制和完善的可复现性。但节点式的工…

系列二、Spring整合单元测试

一、概述 Spring中获取bean最常见的方式是通过ClassPathXmlApplicationContext 或者 AnnotationConfigApplicationContext的getBean()方式获取bean&#xff0c;那么在Spring中如何像在SpringBoot中直接一个类上添加个SpringBootTest注解&#xff0c;即可在类中注入自己想要测试…

pytest-pytest-html测试报告这样做,学完能涨薪3k

在 pytest 中提供了生成html格式测试报告的插件 pytest-html 安装 安装命令如下&#xff1a; pip install pytest-html使用 我们已经知道执行用例的两种方式&#xff0c;pytest.main()执行和命令行执行&#xff0c;而要使用pytest-html生成报告&#xff0c;只需要在执行时加…

飞翔的小鸟小游戏

主类 package APP;import 框架.GameFrame;public class GameApp {public static void main(String[] args) {//游戏的入口new GameFrame();} }场景实物 package 框架;import 图导.Constant; import 图导.GameUtil;import java.awt.*; import java.awt.image.BufferedImage; …

VR模拟仿真技术为司法科普建设注入更多的智慧和力量

虚拟现实(VR)技术已经逐渐渗透到各个领域&#xff0c;包括司法领域&#xff0c;在法学院教学中&#xff0c;VR虚拟现实和web3d开发技术的兴起&#xff0c;让司法教育也突破传统教授式、演练式的教学模式&#xff0c;通过VR特有的沉浸式展示特点&#xff0c;实现了真实法庭效果的…

飞书如何接入ChatGPT-打造个人智能问答助手实现无障碍交流

目录 前言 环境列表 1.飞书设置 2.克隆feishu-chatgpt项目 3.配置config.yaml文件 4.运行feishu-chatgpt项目 5.安装cpolar内网穿透 6.固定公网地址 7.机器人权限配置 8.创建版本 9.创建测试企业 10. 机器人测试 总结 前言 在飞书中创建chatGPT机器人并且对话&am…

目标检测算法 - YOLOv4

文章目录 1. 简介2. YOLOv4整体结构3. Backbone4. Neck 1. 简介 YOLOv4是YOLOv3的改进版。YOLOv4并不是原YOLO项目的作者。发表于CVPR2020。 改进&#xff1a; 主干特征提取网络&#xff1a;Darknet53 -> CSPDarknet53特征金字塔&#xff1a;SPP&#xff0c;PAN分类回归层…

TikTok shop印尼重启电商征程:与当地平台合作开启新篇章!——站斧浏览器

经历了一个半月的间隔&#xff0c;TikTok Shop成功重返印度尼西亚市场。据国际媒体报道&#xff0c;TikTok计划通过与印尼本地电子商务平台的合作&#xff0c;重启其在该国的电商业务。 Temmy Satya Permana&#xff0c;印尼合作社和中小企业部的官员&#xff0c;证实了这一重…

【LeetCode刷题】--59.螺旋矩阵II

59.螺旋矩阵II class Solution {public int[][] generateMatrix(int n) {int[][] res new int[n][n];int count 1;int left 0,right n-1,top 0,bottom n -1;while(left < right && top < bottom){for(int col left;col < right;col){ //从左往右res[to…

[MySQL] MySQL 表的增删查改

本篇文章对mysql表的增删查改进行了详细的举例说明解释。对表的增删查改简称CRUD : Create(创建), Retrieve(读取)&#xff0c;Update(更新)&#xff0c;Delete&#xff08;删除&#xff09;。其中重点是对查询select语句进行了详细解释&#xff0c;并且通过多个实际例子来帮助…