找回密码
 立即注册
首页 业界区 业界 鸿蒙特效教程06-可拖拽网格实现教程

鸿蒙特效教程06-可拖拽网格实现教程

森萌黠 3 天前
鸿蒙特效教程06-可拖拽网格实现教程

本教程适合 HarmonyOS Next 初学者,通过简单到复杂的步骤,一步步实现类似桌面APP中的可拖拽编辑效果。
开发环境准备


  • DevEco Studio 5.0.3
  • HarmonyOS Next API 15
效果预览

我们要实现的效果是一个 Grid 网格布局,用户可以通过长按并拖动来调整应用图标的位置顺序。拖拽完成后,底部会显示当前的排序结果。
1.gif

实现步骤

步骤一:创建基本结构和数据模型

首先,我们需要创建一个基本的页面结构和数据模型。我们将定义一个应用名称数组和一个对应的颜色数组。
  1. @Entry
  2. @Component
  3. struct DragGrid {
  4.   // 应用名称数组
  5.   @State apps: string[] = [
  6.     '微信', '支付宝', 'QQ', '抖音',
  7.     '快手', '微博', '头条', '网易云'
  8.   ];
  9.   
  10.   build() {
  11.     Column() {
  12.       // 这里将放置我们的应用网格
  13.       Text('应用网格示例')
  14.         .fontSize(20)
  15.         .fontColor(Color.White)
  16.     }
  17.     .width('100%')
  18.     .height('100%')
  19.     .backgroundColor('#121212')
  20.   }
  21. }
复制代码
这个基本结构包含一个应用名称数组和一个简单的Column容器。在这个阶段,我们只是显示一个标题文本。
步骤二:使用Grid布局展示应用图标

接下来,我们将使用Grid组件来创建网格布局,并使用ForEach遍历应用数组,为每个应用创建一个网格项。
  1. @Entry
  2. @Component
  3. struct DragGrid {
  4.   @State apps: string[] = [
  5.     '微信', '支付宝', 'QQ', '抖音',
  6.     '快手', '微博', '头条', '网易云'
  7.   ];
  8.   
  9.   build() {
  10.     Column() {
  11.       // 使用Grid组件创建网格布局
  12.       Grid() {
  13.         ForEach(this.apps, (item: string) => {
  14.           GridItem() {
  15.             Column() {
  16.               // 应用图标(暂用占位图)
  17.               Image($r('app.media.startIcon'))
  18.                 .width(60)
  19.                 .aspectRatio(1)
  20.                
  21.               // 应用名称
  22.               Text(item)
  23.                 .fontSize(12)
  24.                 .fontColor(Color.White)
  25.             }
  26.             .padding(10)
  27.           }
  28.         })
  29.       }
  30.       .columnsTemplate('1fr 1fr 1fr 1fr') // 4列等宽布局
  31.       .rowsGap(10) // 行间距
  32.       .columnsGap(10) // 列间距
  33.       .padding(20) // 内边距
  34.     }
  35.     .width('100%')
  36.     .height('100%')
  37.     .backgroundColor('#121212')
  38.   }
  39. }
复制代码
在这一步,我们添加了Grid组件,它具有以下关键属性:

  • columnsTemplate:定义网格的列模板,'1fr 1fr 1fr 1fr'表示四列等宽布局。
  • rowsGap:行间距,设置为10。
  • columnsGap:列间距,设置为10。
  • padding:内边距,设置为20。
每个GridItem包含一个Column布局,里面有一个Image(应用图标)和一个Text(应用名称)。
步骤三:优化图标布局和样式

现在我们有了基本的网格布局,接下来优化图标的样式和布局。我们将创建一个自定义的Builder函数来构建每个应用图标项,并添加一些颜色来区分不同应用。
  1. @Entry
  2. @Component
  3. struct DragGrid {
  4.   @State apps: string[] = [
  5.     '微信', '支付宝', 'QQ', '抖音',
  6.     '快手', '微博', '头条', '网易云',
  7.     '腾讯视频', '爱奇艺', '优酷', 'B站'
  8.   ];
  9.   
  10.   // 定义应用图标颜色
  11.   private appColors: string[] = [
  12.     '#34C759', '#007AFF', '#5856D6', '#FF2D55',
  13.     '#FF9500', '#FF3B30', '#E73C39', '#D33A31',
  14.     '#38B0DE', '#39A5DC', '#22C8BD', '#00A1D6'
  15.   ];
  16.   
  17.   // 创建应用图标项的构建器
  18.   @Builder
  19.   itemBuilder(name: string, index: number) {
  20.     Column({ space: 2 }) {
  21.       // 应用图标
  22.       Image($r('app.media.startIcon'))
  23.         .width(80)
  24.         .padding(10)
  25.         .aspectRatio(1)
  26.         .backgroundColor(this.appColors[index % this.appColors.length])
  27.         .borderRadius(16)
  28.         
  29.       // 应用名称
  30.       Text(name)
  31.         .fontSize(12)
  32.         .fontColor(Color.White)
  33.     }
  34.   }
  35.   
  36.   build() {
  37.     Column() {
  38.       Grid() {
  39.         ForEach(this.apps, (item: string, index: number) => {
  40.           GridItem() {
  41.             this.itemBuilder(item, index)
  42.           }
  43.         })
  44.       }
  45.       .columnsTemplate('1fr 1fr 1fr 1fr')
  46.       .rowsGap(20)
  47.       .columnsGap(20)
  48.       .padding(20)
  49.     }
  50.     .width('100%')
  51.     .height('100%')
  52.     .backgroundColor('#121212')
  53.   }
  54. }
复制代码
在这一步,我们:

  • 添加了appColors数组,定义了各个应用图标的背景颜色。
  • 创建了@Builder itemBuilder函数,用于构建每个应用图标项,使代码更加模块化。
  • 为图标添加了背景颜色和圆角边框,使其更加美观。
  • 在ForEach中添加了index参数,用于获取当前项的索引,以便为不同应用使用不同的颜色。
步骤四:添加拖拽功能

现在我们有了美观的网格布局,下一步是添加拖拽功能。我们需要设置Grid的editMode属性为true,并添加相应的拖拽事件处理函数。
  1. @Entry
  2. @Component
  3. struct DragGrid {
  4.   @State apps: string[] = [
  5.     '微信', '支付宝', 'QQ', '抖音',
  6.     '快手', '微博', '头条', '网易云',
  7.     '腾讯视频', '爱奇艺', '优酷', 'B站'
  8.   ];
  9.   
  10.   private appColors: string[] = [
  11.     '#34C759', '#007AFF', '#5856D6', '#FF2D55',
  12.     '#FF9500', '#FF3B30', '#E73C39', '#D33A31',
  13.     '#38B0DE', '#39A5DC', '#22C8BD', '#00A1D6'
  14.   ];
  15.   
  16.   @Builder
  17.   itemBuilder(name: string) {
  18.     Column({ space: 2 }) {
  19.       Image($r('app.media.startIcon'))
  20.         .draggable(false) // 禁止图片本身被拖拽
  21.         .width(80)
  22.         .padding(10)
  23.         .aspectRatio(1)
  24.         
  25.       Text(name)
  26.         .fontSize(12)
  27.         .fontColor(Color.White)
  28.     }
  29.   }
  30.   
  31.   // 交换两个应用的位置
  32.   changeIndex(a: number, b: number) {
  33.     let temp = this.apps[a];
  34.     this.apps[a] = this.apps[b];
  35.     this.apps[b] = temp;
  36.   }
  37.   
  38.   build() {
  39.     Column() {
  40.       Grid() {
  41.         ForEach(this.apps, (item: string) => {
  42.           GridItem() {
  43.             this.itemBuilder(item)
  44.           }
  45.         })
  46.       }
  47.       .columnsTemplate('1fr 1fr 1fr 1fr')
  48.       .rowsGap(20)
  49.       .columnsGap(20)
  50.       .padding(20)
  51.       .supportAnimation(true) // 启用动画
  52.       .editMode(true) // 启用编辑模式
  53.       // 拖拽开始事件
  54.       .onItemDragStart((_event: ItemDragInfo, itemIndex: number) => {
  55.         return this.itemBuilder(this.apps[itemIndex]);
  56.       })
  57.       // 拖拽放置事件
  58.       .onItemDrop((_event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => {
  59.         if (!isSuccess || insertIndex >= this.apps.length) {
  60.           return;
  61.         }
  62.         this.changeIndex(itemIndex, insertIndex);
  63.       })
  64.       .layoutWeight(1)
  65.     }
  66.     .width('100%')
  67.     .height('100%')
  68.     .backgroundColor('#121212')
  69.   }
  70. }
复制代码
在这一步,我们添加了拖拽功能的关键部分:

  • 设置supportAnimation(true)来启用动画效果。
  • 设置editMode(true)来启用编辑模式,这是实现拖拽功能的必要设置。
  • 添加onItemDragStart事件处理函数,当用户开始拖拽时触发,返回被拖拽项的UI表示。
  • 添加onItemDrop事件处理函数,当用户放置拖拽项时触发,处理位置交换逻辑。
  • 创建changeIndex方法,用于交换数组中两个元素的位置。
  • 在Image上设置draggable(false),确保是整个GridItem被拖拽,而不是图片本身。
步骤五:添加排序结果展示

为了让用户更直观地看到排序结果,我们在网格下方添加一个区域,用于显示当前的应用排序结果。
  1. @Entry
  2. @Component
  3. struct DragGrid {
  4.   // 前面的代码保持不变...
  5.   
  6.   build() {
  7.     Column() {
  8.       // 应用网格部分保持不变...
  9.       
  10.       // 添加排序结果展示区域
  11.       Column({ space: 10 }) {
  12.         Text('应用排序结果')
  13.           .fontSize(16)
  14.           .fontColor(Color.White)
  15.          
  16.         Flex({ wrap: FlexWrap.Wrap, justifyContent: FlexAlign.Center }) {
  17.           ForEach(this.apps, (item: string, index: number) => {
  18.             Text(item)
  19.               .fontSize(12)
  20.               .fontColor(Color.White)
  21.               .backgroundColor(this.appColors[index % this.appColors.length])
  22.               .borderRadius(12)
  23.               .padding({
  24.                 left: 10,
  25.                 right: 10,
  26.                 top: 4,
  27.                 bottom: 4
  28.               })
  29.               .margin(4)
  30.           })
  31.         }
  32.         .width('100%')
  33.       }
  34.       .width('100%')
  35.       .padding(10)
  36.       .backgroundColor('#0DFFFFFF') // 半透明背景
  37.       .borderRadius({ topLeft: 20, topRight: 20 }) // 上方圆角
  38.     }
  39.     .width('100%')
  40.     .height('100%')
  41.     .backgroundColor('#121212')
  42.   }
  43. }
复制代码
在这一步,我们添加了一个展示排序结果的区域:

  • 使用Column容器,顶部显示"应用排序结果"的标题。
  • 使用Flex布局,设置wrap: FlexWrap.Wrap允许内容换行,justifyContent: FlexAlign.Center使内容居中对齐。
  • 使用ForEach循环遍历应用数组,为每个应用创建一个带有背景色的文本标签。
  • 为结果区域添加半透明背景和上方圆角,使其更加美观。
步骤六:美化界面

最后,我们美化整个界面,添加渐变背景和一些视觉改进。
  1. @Entry
  2. @Component
  3. struct DragGrid {
  4.   // 前面的代码保持不变...
  5.   
  6.   build() {
  7.     Column() {
  8.       // 网格和结果区域代码保持不变...
  9.     }
  10.     .width('100%')
  11.     .height('100%')
  12.     .expandSafeArea() // 扩展到安全区域
  13.     .linearGradient({ // 渐变背景
  14.       angle: 135,
  15.       colors: [
  16.         ['#121212', 0],
  17.         ['#242424', 1]
  18.       ]
  19.     })
  20.   }
  21. }
复制代码
在这一步,我们:

  • 添加expandSafeArea()确保内容可以扩展到设备的安全区域。
  • 使用linearGradient创建渐变背景,角度为135度,从深色(#121212)渐变到稍浅的色调(#242424)。
完整代码

以下是完整的实现代码:
  1. @Entry
  2. @Component
  3. struct DragGrid {
  4.   // 应用名称数组,用于显示和排序
  5.   @State apps: string[] = [
  6.     '微信', '支付宝', 'QQ', '抖音',
  7.     '快手', '微博', '头条', '网易云',
  8.     '腾讯视频', '爱奇艺', '优酷', 'B站',
  9.     '小红书', '美团', '饿了么', '滴滴',
  10.     '高德', '携程'
  11.   ];
  12.   
  13.   // 定义应用图标对应的颜色数组
  14.   private appColors: string[] = [
  15.     '#34C759', '#007AFF', '#5856D6', '#FF2D55',
  16.     '#FF9500', '#FF3B30', '#E73C39', '#D33A31',
  17.     '#38B0DE', '#39A5DC', '#22C8BD', '#00A1D6',
  18.     '#FF3A31', '#FFD800', '#4290F7', '#FF7700',
  19.     '#4AB66B', '#2A9AF1'
  20.   ];
  21.   /**
  22.    * 构建单个应用图标项
  23.    * @param name 应用名称
  24.    * @return 返回应用图标的UI组件
  25.    */
  26.   @Builder
  27.   itemBuilder(name: string) {
  28.     // 垂直布局,包含图标和文字
  29.     Column({ space: 2 }) {
  30.       // 应用图标图片
  31.       Image($r('app.media.startIcon'))
  32.         .draggable(false)// 禁止图片本身被拖拽,确保整个GridItem被拖拽
  33.         .width(80)
  34.         .aspectRatio(1)// 保持1:1的宽高比
  35.         .padding(10)
  36.       // 应用名称文本
  37.       Text(name)
  38.         .fontSize(12)
  39.         .fontColor(Color.White)
  40.     }
  41.   }
  42.   /**
  43.    * 交换两个应用在数组中的位置
  44.    * @param a 第一个索引
  45.    * @param b 第二个索引
  46.    */
  47.   changeIndex(a: number, b: number) {
  48.     // 使用临时变量交换两个元素位置
  49.     let temp = this.apps[a];
  50.     this.apps[a] = this.apps[b];
  51.     this.apps[b] = temp;
  52.   }
  53.   /**
  54.    * 构建组件的UI结构
  55.    */
  56.   build() {
  57.     // 主容器,垂直布局
  58.     Column() {
  59.       // 应用网格区域
  60.       Grid() {
  61.         // 遍历所有应用,为每个应用创建一个网格项
  62.         ForEach(this.apps, (item: string) => {
  63.           GridItem() {
  64.             // 使用自定义builder构建网格项内容
  65.             this.itemBuilder(item)
  66.           }
  67.         })
  68.       }
  69.       // 网格样式和行为设置
  70.       .columnsTemplate('1fr '.repeat(4)) // 设置4列等宽布局
  71.       .columnsGap(20) // 列间距
  72.       .rowsGap(20) // 行间距
  73.       .padding(20) // 内边距
  74.       .supportAnimation(true) // 启用动画支持
  75.       .editMode(true) // 启用编辑模式,允许拖拽
  76.       // 拖拽开始事件处理
  77.       .onItemDragStart((_event: ItemDragInfo, itemIndex: number) => {
  78.         // 返回被拖拽项的UI
  79.         return this.itemBuilder(this.apps[itemIndex]);
  80.       })
  81.       // 拖拽放置事件处理
  82.       .onItemDrop((_event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => {
  83.         // 如果拖拽失败或目标位置无效,则不执行操作
  84.         if (!isSuccess || insertIndex >= this.apps.length) {
  85.           return;
  86.         }
  87.         // 交换元素位置
  88.         this.changeIndex(itemIndex, insertIndex);
  89.       })
  90.       .layoutWeight(1) // 使网格区域占用剩余空间
  91.       // 结果显示区域
  92.       Column({ space: 10 }) {
  93.         // 标题文本
  94.         Text('应用排序结果')
  95.           .fontSize(16)
  96.           .fontColor(Color.White)
  97.         // 弹性布局,允许换行
  98.         Flex({ wrap: FlexWrap.Wrap, justifyContent: FlexAlign.Center }) {
  99.           // 遍历应用数组,为每个应用创建一个彩色标签
  100.           ForEach(this.apps, (item: string, index: number) => {
  101.             Text(item)
  102.               .fontSize(12)
  103.               .fontColor(Color.White)
  104.               .backgroundColor(this.appColors[index % this.appColors.length])
  105.               .borderRadius(12)
  106.               .padding({
  107.                 left: 10,
  108.                 right: 10,
  109.                 top: 4,
  110.                 bottom: 4
  111.               })
  112.               .margin(4)
  113.           })
  114.         }
  115.         .width('100%')
  116.       }
  117.       .width('100%')
  118.       .padding(10) // 内边距
  119.       .backgroundColor('#0DFFFFFF') // 半透明背景
  120.       .expandSafeArea() // 扩展到安全区域
  121.       .borderRadius({ topLeft: 20, topRight: 20 }) // 上左右圆角
  122.     }
  123.     // 主容器样式设置
  124.     .width('100%')
  125.     .height('100%')
  126.     .expandSafeArea() // 扩展到安全区域
  127.     .linearGradient({
  128.       angle: 135, // 渐变角度
  129.       colors: [
  130.         ['#121212', 0], // 起点色
  131.         ['#242424', 1] // 终点色
  132.       ]
  133.     })
  134.   }
  135. }
复制代码
Grid组件的关键属性详解

Grid是鸿蒙系统中用于创建网格布局的重要组件,它有以下关键属性:

  • columnsTemplate: 定义网格的列模板。例如'1fr 1fr 1fr 1fr'表示四列等宽布局。'1fr'中的'fr'是fraction(分数)的缩写,表示按比例分配空间。
  • rowsTemplate: 定义网格的行模板。如果不设置,行高将根据内容自动调整。
  • columnsGap: 列之间的间距。
  • rowsGap: 行之间的间距。
  • editMode: 是否启用编辑模式。设置为true时启用拖拽功能。
  • supportAnimation: 是否支持动画。设置为true时,拖拽过程中会有平滑的动画效果。
拖拽功能的关键事件详解

实现拖拽功能主要依赖以下事件:

  • onItemDragStart: 当用户开始拖拽某个项时触发。

    • 参数:event(拖拽事件信息),itemIndex(被拖拽项的索引)
    • 返回值:被拖拽项的UI表示

  • onItemDrop: 当用户放置拖拽项时触发。

    • 参数:event(拖拽事件信息),itemIndex(原始位置索引),insertIndex(目标位置索引),isSuccess(是否成功)
    • 功能:处理元素位置交换逻辑

此外,还有一些可选的事件可以用于增强拖拽体验:

  • onItemDragEnter: 当拖拽项进入某个位置时触发。
  • onItemDragMove: 当拖拽项在网格中移动时触发。
  • onItemDragLeave: 当拖拽项离开某个位置时触发。
小结与进阶提示

通过本教程,我们实现了一个功能完整的可拖拽应用网格界面。主要学习了以下内容:

  • 使用Grid组件创建网格布局
  • 使用@Builder创建可复用的UI构建函数
  • 实现拖拽排序功能
  • 优化UI和用户体验
进阶提示:

  • 可以添加长按震动反馈,增强交互体验。
  • 可以实现数据持久化,保存用户的排序结果。
  • 可以添加编辑模式切换,只有在特定模式下才允许拖拽排序。
  • 可以为拖拽过程添加更丰富的动画效果,如缩放、阴影等。
希望本教程对你有所帮助,让你掌握鸿蒙系统中Grid组件和拖拽功能的使用方法!

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册