下面的demo,实现了部分item不响应拖拽,但动画有有问题,会挤在一起
// 请参考如下Demo
@Entry
@Component
struct GridExample {
@State numbers: string[] = []
scroller: Scroller = new Scroller()
layoutOptions1: GridLayoutOptions = {
regularSize: [1, 1], // 只支持[1, 1]
irregularIndexes: [0], // 索引为0的GridItem占用一行
}
@State text: string = 'drag'
@Builder pixelMapBuilder() { //拖拽过程样式
Column() {
Text(this.text)
.fontSize(16)
.backgroundColor(0xF9CF93)
.width(80)
.height(80)
.textAlign(TextAlign.Center)
}
}
aboutToAppear() {
for (let i = 1;i <= 9; i++) {
this.numbers.push(i + '')
}
}
changeIndex(index1:number, index2:number) { //交换数组中的位置
const temp = this.numbers[index1];
if (index1 > index2) {
this.numbers.splice(index2, 0, temp);
this.numbers.splice(index1 + 1, 1);
} else {
this.numbers.splice(index2 + 1, 0, temp);
this.numbers.splice(index1, 1);
}
}
build() {
Column({ space: 5 }) {
Grid(this.scroller, this.layoutOptions1) {
ForEach(this.numbers, (day: string) => {
GridItem() {
if (day == "1") {
Text(day)
.fontSize(16)
.backgroundColor(0xF9CF93)
.width("100%")
.height(80)
.textAlign(TextAlign.Center)
} else {
Text(day)
.fontSize(16)
.backgroundColor(0xF9CF93)
.width(80)
.height(80)
.textAlign(TextAlign.Center)
}
}
})
}
.columnsTemplate('1fr 1fr 1fr 1fr')
.columnsGap(10)
.rowsGap(10)
.onScrollIndex((first: number) => {
console.info(first.toString())
})
.width('100%')
.backgroundColor(0xFAEEE0)
.height(300)
.supportAnimation(true)
.editMode(true) //设置Grid是否进入编辑模式,进入编辑模式可以拖拽Grid组件内部GridItem
.onItemDragStart((event: ItemDragInfo, itemIndex: number) => { //第一次拖拽此事件绑定的组件时,触发回调。
if (itemIndex == 0) {
return;
}
this.text = this.numbers[itemIndex]
return this.pixelMapBuilder() //设置拖拽过程中显示的图片。
})
.onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => { //绑定此事件的组件可作为拖拽释放目标,当在本组件范围内停止拖拽行为时,触发回调。
// isSuccess=false时,说明drop的位置在grid外部;insertIndex > length时,说明有新增元素的事件发生
if (!isSuccess || insertIndex >= this.numbers.length || insertIndex == 0) {
return
}
console.info('tag' + itemIndex + '', insertIndex + '') //itemIndex拖拽起始位置,insertIndex拖拽插入位置
this.changeIndex(itemIndex, insertIndex)
})
}.width('100%').margin({ top: 5 })
}
}
参考如下Demo: