【HarmonyOS开发】ArkUI中的自定义弹窗

news2024/9/28 23:24:16

弹窗是一种模态窗口,通常用来展示用户当前需要的或用户必须关注的信息或操作。在弹出框消失之前,用户无法操作其他界面内容。ArkUI 为我们提供了丰富的弹窗功能,弹窗按照功能可以分为以下两类:

  • 确认类:例如警告弹窗 AlertDialog。

  • 选择类:包括文本选择弹窗 TextPickerDialog 、日期滑动选择弹窗 DatePickerDialog、时间滑动选择弹窗 TimePickerDialog 等。

您可以根据业务场景,选择不同类型的弹窗。

参考:OpenHarmony 弹窗文档V4.0

 今天我们主要了解一下自定义弹窗的使用

自定义弹窗

自定义弹窗的使用更加灵活,适用于更多的业务场景,在自定义弹窗中您可以自定义弹窗内容,构建更加丰富的弹窗界面。自定义弹窗的界面可以通过装饰器@CustomDialog 定义的组件来实现,然后结合 CustomDialogController 来控制自定义弹窗的显示和隐藏。

1、定义自定义弹窗

@CustomDialog
struct CustomDialogExample {
  // 双向绑定传值
  @Prop title: string
  @Link inputValue: string
  // 弹窗控制器,控制打开/关闭,必须传入,且名称必须为:controller
  controller: CustomDialogController
  // 弹窗中的按钮事件
  cancel: () => void
  confirm: () => void

  // 弹窗中的内容描述
  build() {
    Column() {
      Text(this.title || "是否修改文本框内容?")
        .fontSize(16)
        .margin(24)
        .textAlign(TextAlign.Start)
        .width("100%")
      TextInput({ 
        placeholder: '文本输入框', 
        text: this.inputValue
      })
        .height(60)
        .width('90%')
        .onChange((value: string) => {
          this.textValue = value
        })
      Flex({ justifyContent: FlexAlign.SpaceAround }) {
        Button('取消')
          .onClick(() => {
            this.controller.close()
            this.cancel()
          }).backgroundColor(0xffffff).fontColor(Color.Black)
        Button('确定')
          .onClick(() => {
            this.controller.close()
            this.confirm()
          }).backgroundColor(0xffffff).fontColor(Color.Red)
      }.margin({ bottom: 10 })
    }
  }
}

2、使用自定义弹窗

@Entry
@Component
struct Index {
  @State title: string = '标题'
  @State inputValue: string = '文本框父子组件数据双绑'
  // 定义自定义弹窗的Controller,传入参数和回调函数
  dialogController: CustomDialogController = new CustomDialogController({
    builder: CustomDialogExample({
      cancel: this.onCancel,
      confirm: this.onAccept,
      textValue: $textValue,
      inputValue: $inputValue
    }),
    cancel: this.existApp,
    autoCancel: true,
    alignment: DialogAlignment.Bottom,
    offset: { dx: 0, dy: -20 },
    gridCount: 4,
    customStyle: false
  })

  aboutToDisappear() {
    this.dialogController = undefined // 将dialogController置空
  }

  onCancel() {
    console.info('点击取消按钮', this.inputValue)
  }

  onAccept() {
    console.info('点击确认按钮', this.inputValue)
  }
  
  build() {
    Column() {
       Button('打开自定义弹窗')
        .width('60%')
        .margin({top:320})
        .zIndex(999)
        .onClick(()=>{
          if (this.dialogController != undefined) {
            this.dialogController.open()
          }
        })
    }
    .height('100%')
    .width('100%')
}

3、一个完整的示例(常用网站选择)

export interface HobbyBean {
  label: string;
  isChecked: boolean;
}

export type DataItemType = { value: string }

@Extend(Button) function dialogButtonStyle() {
  .fontSize(16)
  .fontColor("#007DFF")
  .layoutWeight(1)
  .backgroundColor(Color.White)
  .width(500)
  .height(40)
}

@CustomDialog
struct CustomDialogWidget {
  @State hobbyBeans: HobbyBean[] = [];

  @Prop title:string;
  @Prop hobbyResult: Array<DataItemType>;
  @Link hobbies: string;
  private controller: CustomDialogController;

  setHobbiesValue(hobbyBeans: HobbyBean[]) {
    let hobbiesText: string = '';
    hobbiesText = hobbyBeans.filter((isCheckItem: HobbyBean) =>
    isCheckItem?.isChecked)
      .map((checkedItem: HobbyBean) => {
        return checkedItem.label;
      }).join(',');
    this.hobbies = hobbiesText;
  }

  aboutToAppear() {
    // let context: Context = getContext(this);
    // let manager = context.resourceManager;
    // manager.getStringArrayValue($r('app.strarray.hobbies_data'), (error, hobbyResult) => {
    // });
    this.hobbyResult.forEach(item => {
      const hobbyBean = {
        label: item.value,
        isChecked: this.hobbies.includes(item.value)
      }
      this.hobbyBeans.push(hobbyBean);
    });
  }
  build() {
    Column() {
      Text(this.title || "兴趣爱好")
        .fontWeight(FontWeight.Bold)
        .alignSelf(ItemAlign.Start)
        .margin({ left: 24, bottom: 12 })
      List() {
        ForEach(this.hobbyBeans, (itemHobby: HobbyBean) => {
          ListItem() {
            Row() {
              Text(itemHobby.label)
                .fontSize(16)
                .fontColor("#182431")
                .layoutWeight(1)
                .textAlign(TextAlign.Start)
                .fontWeight(500)
                .margin({ left: 24 })
              Toggle({ type: ToggleType.Checkbox, isOn: itemHobby.isChecked })
                .margin({
                  right: 24
                })
                .onChange((isCheck) => {
                  itemHobby.isChecked = isCheck;
                })
            }
          }
          .height(36)
        }, itemHobby => itemHobby.label)
      }
      .margin({
        top: 6,
        bottom: 8
      })
      .divider({
        strokeWidth: 0.5,
        color: "#0D182431"
      })
      .listDirection(Axis.Vertical)
      .edgeEffect(EdgeEffect.None)
      .width("100%")
      // .height(248)

      Row({
        space: 20
      }) {
        Button("关闭")
          .dialogButtonStyle()
          .onClick(() => {
            this.controller.close();
          })
        Blank()
          .backgroundColor("#F2F2F2")
          .width(1)
          .opacity(1)
          .height(25)
        Button("保存")
          .dialogButtonStyle()
          .onClick(() => {
            this.setHobbiesValue(this.hobbyBeans);
            this.controller.close();
          })
      }
    }
    .width("93.3%")
    .padding({
      top: 14,
      bottom: 16
    })
    .borderRadius(32)
    .backgroundColor(Color.White)
  }
}

@Entry
@Component
struct HomePage {
  @State hobbies: string = '';
  @State hobbyResult: Array<DataItemType> = [
    {
      "value": "FaceBook"
    },
    {
      "value": "Google"
    },
    {
      "value": "Instagram"
    },
    {
      "value": "Twitter"
    },
    {
      "value": "Linkedin"
    }
  ]
  private title: string = '常用网站'
  customDialogController: CustomDialogController = new CustomDialogController({
    builder: CustomDialogWidget({
      hobbies: $hobbies,
      hobbyResult: this.hobbyResult,
      title: this.title
    }),
    alignment: DialogAlignment.Bottom,
    customStyle: true,
    offset: { dx: 0,dy: -20 }
  });

  build() {
    Column() {
      Button('打开自定义弹窗')
        .width('60%')
        .margin({top: 50})
        .zIndex(999)
        .onClick(()=>{
          if (this.customDialogController != undefined) {
            this.customDialogController.open()
          }
        })
      Text(this.hobbies).fontSize(16).padding(24)
    }
    .width('100%')
  }
}

参考:https://gitee.com/harmonyos/codelabs/tree/master/MultipleDialog

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1323308.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

GitBook安装及使用——使用 Markdown 创建你自己的博客网站和电子书

目录 前言一、依赖环境二、gitbook安装使用1.安装 gitbook-cli2.安装 gitbook3.Gitbook初始化4.创建你的文章5.修改 SUMMARY.md 和 README.md6.编译生成静态网页7.运行以便在浏览器预览8.运行效果 前言 GitBook是一个命令行工具&#xff0c;用于使用 Markdown 构建漂亮的博客网…

npm login报错:Public registration is not allowed

npm login报错:Public registration is not allowed 1.出现场景2.解决 1.出现场景 npm login登录时,出现 2.解决 将自己的npm镜像源改为npm的https://registry.npmjs.org/这个&#xff0c;解决&#xff01;

鸿蒙4.0核心技术-WebGL开发

场景介绍 WebGL主要帮助开发者在前端开发中完成图形图像的相关处理&#xff0c;比如绘制彩色图形等。 接口说明 表1 WebGL主要接口列表 接口名描述canvas.getContext获取canvas对象上下文。webgl.createBuffer(): WebGLBuffernullwebgl.bindBuffer(target: GLenum, buffer: …

服务器数据恢复-EMC存储raid5磁盘物理故障离线的数据恢复案例

服务器数据恢复环境&故障&#xff1a; 一台emc某型号存储服务器&#xff0c;存储服务器上组建了一组raid5磁盘阵列&#xff0c;阵列中有两块磁盘作为热备盘使用。存储服务器在运行过程中有两块磁盘出现故障离线&#xff0c;但是只有一块热备盘激活&#xff0c;最终导致该ra…

Gin之GORM多表关联查询(多对多;自定义预加载SQL)

数据库三个,如下: 注意:配置中间表的时候,表设计层面最好和配置的其他两张表契合,例如其他两张表为fate内的master和slave;要整合其对应关系的话,设计中间表的结构为master_id和slave_id最好(不然会涉及重写外键的操作) 重写外键(介绍) 对于 many2many 关系,连接表…

智能优化算法应用:基于黑寡妇算法3D无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用&#xff1a;基于黑寡妇算法3D无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用&#xff1a;基于黑寡妇算法3D无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.黑寡妇算法4.实验参数设定5.算法结果6.参考文…

Jenkins Docker Cloud在Linux应用开发CI中的实践

Jenkins Docker Cloud在Linux应用开发CI中的实践 背景 通过代码提交自动触发CI自动构建、编译、打包是任何软件开发组织必不可少的基建&#xff0c;可以最大程度保证产物的一致性&#xff0c;方便跨组跨部门协作&#xff0c;代码MR等。 Docker在流水线中越来越重要&#xff…

iPhone手机开启地震预警功能

iPhone手机开启地震预警功能 地震预警告警开启方式 地震预警 版权&#xff1a;成都高新减灾研究所 告警开启方式

蜘点云原生之 KubeSphere 落地实践过程

作者&#xff1a;池晓东&#xff0c;蜘点商业网络服务有限公司技术总监&#xff0c;从事软件开发设计 10 多年&#xff0c;喜欢研究各类新技术&#xff0c;分享技术。 来源&#xff1a;本文由 11 月 25 日广州站 meetup 中讲师池晓东整理&#xff0c;整理于该活动中池老师所分享…

YOLOv8改进 | 主干篇 | 轻量级网络ShuffleNetV2(附代码+修改教程)

一、本文内容 本文给大家带来的改进内容是ShuffleNetV2&#xff0c;这是一种为移动设备设计的高效CNN架构。其在ShuffleNetV1的基础上强调除了FLOPs之外&#xff0c;还应考虑速度、内存访问成本和平台特性。(我在YOLOv8n上修改该主干降低了GFLOPs,但是参数量还是有一定上涨&am…

【Docker】基础篇

文章目录 Docker为什么出现容器和虚拟机关于虚拟机关于Docker二者区别&#xff1a; Docker的基本组成相关概念-镜像&#xff0c;容器&#xff0c;仓库安装Docker卸载docker阿里云镜像加速docker run的原理**为什么容器比虚拟机快**Docker的常用命令1.帮助命令2.镜像相关命令3.容…

C语言—每日选择题—Day51

第一题 1. 对于函数void f(int x);&#xff0c;下面调用正确的是&#xff08;&#xff09; A&#xff1a;int y f(9); B&#xff1a;f(9); C&#xff1a;f( f(9) ); D&#xff1a;xf(); 答案及解析 B 函数调用要看返回值和传参是否正确&#xff1b; A&#xff1a;错误&#xf…

【ArcGIS微课1000例】0081:ArcGIS指北针乱码解决方案

问题描述&#xff1a; ArcGIS软件在作图模式下插入指北针&#xff0c;出现指北针乱码&#xff0c;如下图所示&#xff1a; 问题解决 下载并安装字体&#xff08;配套实验数据包0081.rar中获取&#xff09;即可解决该问题。 正常的指北针选择器&#xff1a; 专栏介绍&#xff…

Hadoop3.x完全分布式模式下slaveDataNode节点未启动调整

目录 前言 一、问题重现 1、查询Hadoop版本 2、集群启动Hadoop 二、问题分析 三、Hadoop3.x的集群配置 1、停止Hadoop服务 2、配置workers 3、从节点检测 4、WebUI监控 总结 前言 在大数据的世界里&#xff0c;Hadoop绝对是一个值得学习的框架。关于Hadoop的知识&…

elementui中的el-table,当使用fixed属性时,table主体会遮挡住滚动条的大半部分,导致很难选中。

情况&#xff1a; 解决&#xff1a; el-table加个类&#xff0c;这里取为class"table" 然后是样式部分&#xff1a; <style scoped lang"scss"> ::v-deep.table {// 滚动条高度调整::-webkit-scrollbar {height: 15px;}// pointer-events 的基本信…

一款电压检测LVD

一、基本概述 The TX61C series devices are a set of three terminal low power voltage detectors implemented in CMOS technology. Each voltage detector in the series detects a particular fixed voltage ranging from 0.9V to 5.0V. The voltage detectors consist…

使用Axure的中继器的交互动作解决增删改查h

&#x1f3ac; 艳艳耶✌️&#xff1a;个人主页 &#x1f525; 个人专栏 &#xff1a;《产品经理如何画泳道图&流程图》 ⛺️ 越努力 &#xff0c;越幸运 目录 一、中继器的交互 1、什么是中继器的交互 2、Axure中继器的交互 3、如何使用中继器&#xff1f; 二…

✺ch7——光照

目录 光照模型光源材质ADS光照计算实现ADS光照Gouraud着色&#xff08;双线性光强插值法&#xff09; Phong着色Blinn-Phong反射模型结合光照与纹理补充说明 光照模型 光照模型(lighting model)有时也称为着色模型(shading model)&#xff0c;在着色器编程存在的情况下&#x…

Flask重定向后无效果前端无跳转无反应问题

在网上搜了一下并没有什么好的解决方案&#xff0c;有的话也只是告诉你如何修改代码&#xff0c;并没有讲明白其中的原理以及导致问题的核心&#xff0c;因此特意去了解了一下HTTP的规范找到了答案 问题说明 问题出现的流程大致都是前端发送Ajax请求给后端&#xff0c;进行一些…

redis 7.2.3 官方配置文件 redis.conf sentinel.conf

文章目录 Intro解压配置使用等官方配置文件模板redis.conf 仅配置项redis.conf 完整版(配置项注释)sentinel.conf 仅配置项sentinel.conf 完整版(配置项注释) Intro 在下载页面&#xff1a;https://redis.io/download/ 下载最新版本的redis&#xff1a; https://github.com/re…