HarmonyOS 鸿蒙Next 有没有大佬指点一下 拖拽 listitem 里面的按钮,实现编辑 listitem 顺序

HarmonyOS 鸿蒙Next 有没有大佬指点一下 拖拽 listitem 里面的按钮,实现编辑 listitem 顺序 大佬救救孩子吧。。
或者指点一下,touchevent 里面能不能拿到上一级组件的坐标。。。
或者讲讲那个拖拽事件。。。事件是有了,但是怎么启动拖拽呢。。。

3 回复

一般来说长按开启拖拽,Grid的话还需要设置editMode为true

更多关于HarmonyOS 鸿蒙Next 有没有大佬指点一下 拖拽 listitem 里面的按钮,实现编辑 listitem 顺序的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


您好楼主:

关于您提出的关于listitem和touchevent 的问题,找到了如下文档以供参考:

关于listitem的文档:
[ListItem-HarmonyOS应用开发](https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/ts-container-listitem-0000001427902476-V3#ZH-CN_TOPIC_0000001523488862__swipeedgeeffect9%E6%9E%9A%E4%B8%BE%E8%AF%B4%E6%98%8E)

关于touchevent的中文文档:
[触摸事件-HarmonyOS应用开发](https://developer.harmonyos.com/cn/docs/documentation/doc-references/ts-universal-events-touch-0000001281001286)

关于touchevent的英文文档:
[TouchEvent-HarmonyOS应用开发](https://developer.harmonyos.com/cn/docs/documentation/doc-references/touchevent-0000001054558959#ZH-CN_TOPIC_0000001054558959__TouchEvent--)

在HarmonyOS中,实现拖拽ListItem中的按钮以编辑ListItem顺序,可以通过以下步骤完成:

  1. 布局定义:在xml布局文件中定义ListItem和按钮。例如:

    <ListItem
        ohos:id="$+id/list_item"
        ohos:width="match_parent"
        ohos:height="wrap_content">
        <Button
            ohos:id="$+id/drag_button"
            ohos:width="wrap_content"
            ohos:height="wrap_content"
            ohos:text="拖拽"/>
    </ListItem>
    
  2. 事件监听:为按钮设置触摸事件监听器,处理拖拽逻辑。例如:

    Button dragButton = (Button) findComponentById(ResourceTable.Id_drag_button);
    dragButton.setTouchEventListener(new Component.TouchEventListener() {
        @Override
        public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
            switch (touchEvent.getAction()) {
                case TouchEvent.PRIMARY_POINT_DOWN:
                    // 开始拖拽
                    break;
                case TouchEvent.POINT_MOVE:
                    // 处理拖拽移动
                    break;
                case TouchEvent.PRIMARY_POINT_UP:
                    // 结束拖拽
                    break;
            }
            return true;
        }
    });
    
  3. 数据更新:在拖拽过程中,更新ListItem的顺序数据。例如:

    List<Data> dataList = ...; // 数据列表
    int fromPosition = ...; // 起始位置
    int toPosition = ...; // 目标位置
    Collections.swap(dataList, fromPosition, toPosition);
    
  4. UI刷新:更新ListItem的顺序后,刷新UI以反映变化。例如:

    ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
    listContainer.setItemProvider(new ListItemProvider(dataList));
    

通过以上步骤,可以在HarmonyOS中实现拖拽ListItem内的按钮以编辑ListItem顺序的功能。

回到顶部