本文将带你从零开始学习 HarmonyOS 中的 Grid 网格拖拽功能,通过实际案例让你轻松掌握这一常用的交互特性。
想象一下你在手机上编辑九宫格照片,或者重新排列桌面应用图标的场景。当你长按一张照片或应用图标,然后拖拽到新位置时,其他元素会自动调整位置——这就是 Grid 网格拖拽功能!
在 HarmonyOS 中,Grid 网格拖拽主要依靠三个核心技术:
Grid 是 HarmonyOS 提供的网格布局容器,类似于前端的 CSS Grid。它可以:
HarmonyOS 的手势系统让我们能够:
为了提供流畅的用户体验,我们使用显式动画:
这是最常见的场景,比如相册的九宫格编辑功能。
// 设置网格的基本属性
@Component
struct GridDragDemo {
build() {
Grid() {
// 网格内容
}
.columnsTemplate('1fr 1fr 1fr') // 创建3列等宽布局
.columnsGap(10) // 列间距10vp
.rowsGap(10) // 行间距10vp
.scrollBar(BarState.Off) // 隐藏滚动条
}
}
Grid() {
// 内容
}
.editMode(true) // 关键:开启编辑模式
.supportAnimation(true) // 开启拖拽动画支持
.onItemDragStart((event, itemIndex) => {
// 拖拽开始时的处理逻辑
console.log(`开始拖拽第 ${itemIndex} 个元素`)
})
.onItemDrop((event, itemIndex, insertIndex, isSuccess) => {
// 拖拽结束时的处理逻辑
if (isSuccess) {
// 交换数组中元素的位置
this.swapArrayElements(itemIndex, insertIndex)
}
})
// 交换数组中两个元素的位置
private swapArrayElements(fromIndex: number, toIndex: number) {
const temp = this.dataArray[fromIndex]
this.dataArray[fromIndex] = this.dataArray[toIndex]
this.dataArray[toIndex] = temp
}
editMode(true)
是启用拖拽的关键属性supportAnimation(true)
让拖拽过程更加流畅onItemDrop
回调中完成在智能家居或设备管理场景中,不同设备可能需要不同大小的网格空间。
GridItem() {
// 内容
}
.columnStart(0) // 起始列
.columnEnd(1) // 结束列(占用2列)
.rowStart(0) // 起始行
.rowEnd(0) // 结束行(占用1行)
GridItem() {
// 内容
}
.gesture(
GestureGroup(GestureMode.Sequence,
LongPressGesture({ fingers: 1, repeat: false, duration: 300 })
.onAction(() => {
// 长按开始拖拽
}),
PanGesture()
.onActionStart(() => {
// 拖拽开始
})
.onActionUpdate((event) => {
// 拖拽过程中
})
.onActionEnd(() => {
// 拖拽结束
})
)
)
columnStart/End
和 rowStart/End
有时候我们希望元素可以直接拖拽,无需长按触发。
直接绑定拖拽手势,跳过长按步骤:
GridItem() {
// 内容
}
.gesture(
PanGesture()
.onActionStart(() => {
// 直接开始拖拽
})
.onActionUpdate((event) => {
// 拖拽中更新位置
})
.onActionEnd(() => {
// 拖拽结束处理
})
)
为了提供更好的视觉反馈,我们可以在长按时添加抖动动画。
// 添加抖动动画的状态变量
@State isShaking: boolean = false
// 抖动动画函数
private startShakeAnimation() {
this.isShaking = true
// 使用显式动画实现抖动效果
animateTo({
duration: 100,
iterations: -1, // 无限循环
playMode: PlayMode.Alternate
}, () => {
// 抖动的位移效果
})
}
// 停止抖动
private stopShakeAnimation() {
this.isShaking = false
// 停止动画,恢复原位
}
当你需要在两个不同的 Grid 容器间移动元素时,可以使用 HarmonyOS 提供的 GridObjectSortComponent
组件。
import { GridObjectSortComponent } from "@ohos.arkui.advanced.GridObjectSortComponent";
// 在你的组件中使用
GridObjectSortComponent({
// 配置参数
});
GridObjectSortComponent
的源码进行定制开发supportAnimation(true)
让用户体验更流畅editMode(true)
导致无法拖拽Grid 网格拖拽是 HarmonyOS 开发中的重要交互特性,通过本文的学习,你应该掌握了:
现在你可以在自己的项目中实践这些技术,创造出更加生动有趣的用户界面了!
希望这篇文章对你的 HarmonyOS 学习之路有所帮助!如果有任何问题,欢迎交流讨论。