前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >鸿蒙应用开发-自定义可删除列表弹窗

鸿蒙应用开发-自定义可删除列表弹窗

作者头像
夜雨飘零
发布2024-05-26 16:11:13
480
发布2024-05-26 16:11:13
举报
文章被收录于专栏:CSDN博客CSDN博客

功能介绍:

自定义列表弹窗,可以对弹窗的列表点击删除,参考文档创建列表,自定义弹窗文档自定义弹窗(CustomDialog)

知识点:

  1. 熟悉对List控件的使用。
  2. 熟悉对List点击删除
  3. 熟悉自定义弹窗。

使用环境:

  • API 9
  • DevEco Studio 4.0 Release
  • Windows 11
  • Stage模型
  • ArkTS语言

所需权限:

  1. 无需权限

效果图:

核心代码:

src/main/ets/model/Intention.ets是定义列表内容的实体类:

代码语言:javascript
复制
export class Intention {
  key: string
  name: string

  constructor(name: string) {
    this.key = `${Date.now()}_${Math.floor(Math.random() * 1000)}`
    this.name = name
  }
}

src/main/ets/model/IntentionDataSource.ets是列表的操作类。

代码语言:javascript
复制
import { Intention } from './Intention';

class BasicDataSource implements IDataSource {
  private listeners: DataChangeListener[] = [];
  private originDataArray: Array<Intention> = new Array<Intention>();

  public totalCount(): number {
    return 0;
  }

  public getData(index: number): Intention {
    return this.originDataArray[index];
  }

  registerDataChangeListener(listener: DataChangeListener): void {
    if (this.listeners.indexOf(listener) < 0) {
      console.info('add listener');
      this.listeners.push(listener);
    }
  }

  unregisterDataChangeListener(listener: DataChangeListener): void {
    const pos = this.listeners.indexOf(listener);
    if (pos >= 0) {
      console.info('remove listener');
      this.listeners.splice(pos, 1);
    }
  }

  notifyDataReload(): void {
    this.listeners.forEach(listener => {
      listener.onDataReloaded();
    })
  }

  notifyDataAdd(index: number): void {
    this.listeners.forEach(listener => {
      listener.onDataAdd(index);
    })
  }

  notifyDataChange(index: number): void {
    this.listeners.forEach(listener => {
      listener.onDataChange(index);
    })
  }

  notifyDataDelete(index: number): void {
    this.listeners.forEach(listener => {
      listener.onDataDelete(index);
    })
  }
}

export class IntentionDataSource extends BasicDataSource {
  private dataArray: Array<Intention> = new Array<Intention>();

  public totalCount(): number {
    return this.dataArray.length;
  }

  public getData(index: number): Intention {
    return this.dataArray[index];
  }

  public getAllData(): Array<Intention>{
    return this.dataArray
  }

  public addData(index: number, data: Intention): void {
    this.dataArray.splice(index, 0, data);
    this.notifyDataAdd(index);
  }

  public pushData(data: Intention): void {
    this.dataArray.push(data);
    this.notifyDataAdd(this.dataArray.length - 1);
  }

  public pushDataArray(data: Array<Intention>): void {
    this.dataArray.push(...data);
    this.notifyDataAdd(this.dataArray.length - 1);
  }

  public deleteData(index: number): void {
    this.dataArray.splice(index, 1);
    this.notifyDataDelete(index);
  }

  public reloadData(): void {
    this.notifyDataReload();
  }
}

src/main/ets/view/CustomDialog.ets是自定义弹窗。

代码语言:javascript
复制
import { Intention } from '../model/Intention'
import { IntentionDataSource } from '../model/IntentionDataSource'

@CustomDialog
export struct AddIntentionDialog {
  private controller: CustomDialogController
  private intentionListDataSource: IntentionDataSource
  cancel: () => void
  confirm: (intentions:Array<Intention>) => void

  build() {
    Column() {
      Text('任务列表')
        .fontSize(22)
        .fontWeight(FontWeight.Bold)
        .margin({ top: 20, bottom: 20 })

      List({ space: 5 }) {
        LazyForEach(this.intentionListDataSource, (item: Intention, index: number) => {
          ListItem() {
            Row() {
              Column() {
                Text(item?.name)
                  .padding(5)
              }
              .width('50%')
              .alignItems(HorizontalAlign.Center)

              Column() {
                Button('删除')
                  .onClick(() => {
                    // 删除数据
                    this.intentionListDataSource.deleteData(index)
                    // 重置所有子组件的index索引
                    this.intentionListDataSource.reloadData()
                  })
              }
              .width('50%')
              .alignItems(HorizontalAlign.Center)
            }
            .width('100%')
          }
        }, (item: Intention, index: number) => item.key + index.toString()) // 不能忽略这个
      }
      .width('100%')

      Flex({ justifyContent: FlexAlign.SpaceAround }) {
        Button("取消")
          .onClick(() => {
            this.controller.close()
            this.cancel()
          })
          .fontColor(Color.Black)
          .backgroundColor(Color.Pink)
          .margin({ top: 20, bottom: 20 })
        Button("确定")
          .onClick(() => {
            this.controller.close()
            this.confirm(this.intentionListDataSource.getAllData())
          })
          .fontColor(Color.White)
          .backgroundColor(Color.Blue)
          .margin({ top: 20, bottom: 20 })
      }
    }
  }
}

页面代码如下:

代码语言:javascript
复制
import { AddIntentionDialog } from '../view/CustomDialog'
import { Intention } from '../model/Intention'
import { IntentionDataSource } from '../model/IntentionDataSource'

@Entry
@Component
struct Index {
  private dialogController: CustomDialogController
  private intentionList = new Array<Intention>()
  private intentionIndex: number = 0;

  build() {
    Column() {
      Button('添加数据&显示弹窗')
        .onClick(() => {
          for (let index = this.intentionIndex; index <  this.intentionIndex + 4; index++) {
            let intention: Intention = new Intention(`任务${index}`)
            this.intentionList.push(intention)
            console.info(`任务${index},列表大小:${this.intentionList.length}`)
          }
          this.intentionIndex =  this.intentionIndex + 4
          // 显示弹窗
          this.show()
        })
        .width('100%')
        .margin({ top: 10 })
      Button('显示弹窗')
        .onClick(() => {
          // 显示弹窗
          this.show()
        })
        .width('100%')
        .margin({ top: 10 })
    }.width('100%')
  }

  // 显示弹窗
  show() {
    let intentionListDataSource: IntentionDataSource = new IntentionDataSource()
    intentionListDataSource.pushDataArray(this.intentionList)
    this.dialogController = new CustomDialogController({
      builder: AddIntentionDialog({
        intentionListDataSource: intentionListDataSource,
        cancel: () => {
          console.info('点击取消按钮')
        },
        confirm: (intentions) => {
          console.info('点击确认按钮')
          this.intentionList = intentions
        },
      }),
      // 点击其他空白区域自动关闭弹窗
      autoCancel: true,
      // 弹窗的位置
      alignment: DialogAlignment.Center,
    })
    this.dialogController.open()
  }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-02-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档