【HarmonyOS5.0实战开发】基于promptAction全局弹窗

328 篇文章 0 订阅
315 篇文章 0 订阅

场景一:创建并显示全局自定义弹窗

0030086000558681258.20240709172206.90127949638149605200154059439621.gif

方案

可以使用openCustomDialog接口, 创建并弹出dialogContent对应的自定义弹窗,使用Promise异步回调。

创建Params类方便开发者进行传参的,开发者可以在@Builder里自定义组件的内容,宽度跟随子节点自适应,圆角为0,弹窗背景色为透明色;

let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message))

上述代码中uiContext代表上下文,wrapBuilder(buildText)代表自定义节点,new Params(this.message)代表传参。

核心代码

import { BusinessError } from '@ohos.base';
import { ComponentContent } from "@ohos.arkui.node";

class Params {
  text: string = ""
  constructor(text: string) {
    this.text = text;
  }
}//传参

@Builder
function buildText(params: Params) {
  Row(){
    Column() {
      Text(params.text)
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .margin({bottom: 36})
    }.backgroundColor('#FFF0F0F0')
  }
  .height("100%")
} //自定义组件的内容

@Entry
@Component
struct Index {
  @State message: string = "显示TOAST"

  build() {
    Row() {
      Column() {
        Button("click me")
          .onClick(() => {
            let uiContext = this.getUIContext();
            let promptAction = uiContext.getPromptAction();
            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));//上下文、自定义节点、传参
            try {
              promptAction.openCustomDialog(contentNode);
            } catch (error) {
              let message = (error as BusinessError).message;
              let code = (error as BusinessError).code;
              console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
            };
          })
      }
      .width('100%')
      .height('100%')
    }
    .height('100%')
  }
}

import { BusinessError } from '@ohos.base';
import { ComponentContent } from "@ohos.arkui.node";

class Params {
  text: string = ""
  constructor(text: string) {
    this.text = text;
  }
}//传参

@Builder
function buildText(params: Params) {
  Row(){
    Column() {
      Text(params.text)
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .margin({bottom: 36})
    }.backgroundColor('#FFF0F0F0')
  }
  .height("100%")
} //自定义组件的内容

@Entry
@Component
struct Index {
  @State message: string = "显示TOAST"

  build() {
    Row() {
      Column() {
        Button("click me")
          .onClick(() => {
            let uiContext = this.getUIContext();
            let promptAction = uiContext.getPromptAction();
            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));//上下文、自定义节点、传参
            try {
              promptAction.openCustomDialog(contentNode);
            } catch (error) {
              let message = (error as BusinessError).message;
              let code = (error as BusinessError).code;
              console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
            };
          })
      }
      .width('100%')
      .height('100%')
    }
    .height('100%')
  }
}

场景二:全局弹窗拦截返回并监听返回事件

0030086000558681258.20240709172634.28456979347095998290029537992812.gif

方案

onWillDismiss Callback,当用户执行点击遮障层关闭、左滑/右滑、三键back、键盘ESC关闭交互操作时,如果注册该回调函数,则不会立刻关闭弹窗。在回调函数中可以通过reason得到阻拦关闭弹窗的操作类型,从而根据原因选择是否能关闭弹窗。

image.png

当前组件返回的reason中,暂不支持CLOSE_BUTTON的枚举值。

核心代码

import { BusinessError } from '@ohos.base';
import { ComponentContent } from "@ohos.arkui.node";

class Params {
  text: string = ""

  constructor(text: string) {
    this.text = text;
  }
} //传参

@Builder
function buildText(params: Params) {
  Row() {
    Column() {
      Text(params.text)
        .fontSize(20)
        .textAlign(TextAlign.Center)
        .fontWeight(FontWeight.Bold)
        .padding(8)
      Text('方便为你提供本地新闻和天气信息,并且根据您的位置信息发现附近的免费WiFi')
        .fontSize(16)
        .textAlign(TextAlign.Center)
        .padding({ left: 14, right: 14 })
        .margin({ top: -4 })
      Row({ space: 64 }) {
        Button("不允许")
          .onClick(() => {
            let link1: SubscribedAbstractProperty<number> = storage.link('PropA');
            let numsss = link1.get()
            console.log('nums', link1.get())
            link1.set(++numsss)
          })

        Button("允许")
      }
      .padding(24)
    }
    .width("90%")
    .borderRadius(8)
    .backgroundColor('#FFF0F0F0')
  }
  .height("100%")
} //自定义组件的内容

let para: Record<string, number> = { 'PropA': 1 };
let storage: LocalStorage = new LocalStorage(para); // 创建新实例并使用给定对象初始化

@Entry(storage)
@Component
struct Index {
  @State message: string = "允许“应用”在您使用该应用时访问您的位置吗?"
  @LocalStorageLink('uiContext') aaa: UIContext = this.getUIContext();
  @LocalStorageLink('PropAA') shjsh: ComponentContent<Params> | null = null
  @LocalStorageLink('PropA') @Watch('onchang') nums: number = 0;

  onchang() {
    try {
      this.aaa.getPromptAction().closeCustomDialog(this.shjsh);
    } catch (error) {
      let message = (error as BusinessError).message;
      let code = (error as BusinessError).code;
      console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
    }
  }

  build() {
    Row() {
      Column() {
        Button("click me")
          .onClick(() => {
            let uiContext = this.getUIContext();
            let promptAction = uiContext.getPromptAction();
            let contentNode =
              new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)); // 上下文、自定义节点、传参
            this.shjsh = contentNode
            try {
              promptAction.openCustomDialog(contentNode,
                {
                  onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
                    console.info("reason" + JSON.stringify(dismissDialogAction.reason))
                    console.log("dialog onWillDismiss")
                  }
                });
            } catch (error) {
              let message = (error as BusinessError).message;
              let code = (error as BusinessError).code;
              console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
            }
          })
      }
      .width('100%')
      .height('100%')
    }
    .height('100%')
  }
}

import { BusinessError } from '@ohos.base';
import { ComponentContent } from "@ohos.arkui.node";

class Params {
  text: string = ""

  constructor(text: string) {
    this.text = text;
  }
} //传参

@Builder
function buildText(params: Params) {
  Row() {
    Column() {
      Text(params.text)
        .fontSize(20)
        .textAlign(TextAlign.Center)
        .fontWeight(FontWeight.Bold)
        .padding(8)
      Text('方便为你提供本地新闻和天气信息,并且根据您的位置信息发现附近的免费WiFi')
        .fontSize(16)
        .textAlign(TextAlign.Center)
        .padding({ left: 14, right: 14 })
        .margin({ top: -4 })
      Row({ space: 64 }) {
        Button("不允许")
          .onClick(() => {
            let link1: SubscribedAbstractProperty<number> = storage.link('PropA');
            let numsss = link1.get()
            console.log('nums', link1.get())
            link1.set(++numsss)
          })

        Button("允许")
      }
      .padding(24)
    }
    .width("90%")
    .borderRadius(8)
    .backgroundColor('#FFF0F0F0')
  }
  .height("100%")
} //自定义组件的内容

let para: Record<string, number> = { 'PropA': 1 };
let storage: LocalStorage = new LocalStorage(para); // 创建新实例并使用给定对象初始化

@Entry(storage)
@Component
struct Index {
  @State message: string = "允许“应用”在您使用该应用时访问您的位置吗?"
  @LocalStorageLink('uiContext') aaa: UIContext = this.getUIContext();
  @LocalStorageLink('PropAA') shjsh: ComponentContent<Params> | null = null
  @LocalStorageLink('PropA') @Watch('onchang') nums: number = 0;

  onchang() {
    try {
      this.aaa.getPromptAction().closeCustomDialog(this.shjsh);
    } catch (error) {
      let message = (error as BusinessError).message;
      let code = (error as BusinessError).code;
      console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
    }
  }

  build() {
    Row() {
      Column() {
        Button("click me")
          .onClick(() => {
            let uiContext = this.getUIContext();
            let promptAction = uiContext.getPromptAction();
            let contentNode =
              new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)); // 上下文、自定义节点、传参
            this.shjsh = contentNode
            try {
              promptAction.openCustomDialog(contentNode,
                {
                  onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
                    console.info("reason" + JSON.stringify(dismissDialogAction.reason))
                    console.log("dialog onWillDismiss")
                  }
                });
            } catch (error) {
              let message = (error as BusinessError).message;
              let code = (error as BusinessError).code;
              console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
            }
          })
      }
      .width('100%')
      .height('100%')
    }
    .height('100%')
  }
}

场景三:自定义弹窗样式

样式一:渐隐渐显的方式弹出

效果图

0030086000558681258.20240709173116.39430049639085962296229905964733.gif

方案

promptAction.openCustomDialog接口,弹窗的样式相当于customdialog设置customStyle为true时;此时弹窗的样式完全按照dialogContent中设置的样式显示,完全由开发者自己来定义。

核心代码

import { BusinessError } from '@ohos.base';
import { ComponentContent } from "@ohos.arkui.node";

class Params {
  text: string = ""

  constructor(text: string) {
    this.text = text;
  }
} //传参

@Builder
function buildText(params: Params) {
  Row(){
    Column() {
      Text(params.text)
        .fontSize(20)
        .textAlign(TextAlign.Center)
        .fontWeight(FontWeight.Bold)
        .padding(8)
      Text('方便为你提供本地新闻和天气信息,并且根据您的位置信息发现附近的免费WiFi')
        .fontSize(16)
        .textAlign(TextAlign.Center)
        .padding({ left:14,right:14})
        .margin({top:-4})
      Row({space:64}){
        Button("不允许")
        Button("允许")
      }
      .padding(24)
    }
    .width("90%")
    .borderRadius(8)
    .backgroundColor('#FFF0F0F0')
  }
  .height("100%")
} //自定义组件的内容

@Entry
@Component
struct Index {
  @State message: string = "允许“应用”在您使用该应用时访问您的位置吗?"

  build() {
    Row() {
      Column() {
        Button("click me")
          .onClick(() => {
            let uiContext = this.getUIContext();
            let promptAction = uiContext.getPromptAction();
            let contentNode =
              new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)); //上下文、自定义节点、传参
            try {
              promptAction.openCustomDialog(contentNode);
            } catch (error) {
              let message = (error as BusinessError).message;
              let code = (error as BusinessError).code;
              console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
            }
          })
      }
      .width('100%')
      .height('100%')
    }
    .height('100%')
  }
}

import { BusinessError } from '@ohos.base';
import { ComponentContent } from "@ohos.arkui.node";

class Params {
  text: string = ""

  constructor(text: string) {
    this.text = text;
  }
} //传参

@Builder
function buildText(params: Params) {
  Row(){
    Column() {
      Text(params.text)
        .fontSize(20)
        .textAlign(TextAlign.Center)
        .fontWeight(FontWeight.Bold)
        .padding(8)
      Text('方便为你提供本地新闻和天气信息,并且根据您的位置信息发现附近的免费WiFi')
        .fontSize(16)
        .textAlign(TextAlign.Center)
        .padding({ left:14,right:14})
        .margin({top:-4})
      Row({space:64}){
        Button("不允许")
        Button("允许")
      }
      .padding(24)
    }
    .width("90%")
    .borderRadius(8)
    .backgroundColor('#FFF0F0F0')
  }
  .height("100%")
} //自定义组件的内容

@Entry
@Component
struct Index {
  @State message: string = "允许“应用”在您使用该应用时访问您的位置吗?"

  build() {
    Row() {
      Column() {
        Button("click me")
          .onClick(() => {
            let uiContext = this.getUIContext();
            let promptAction = uiContext.getPromptAction();
            let contentNode =
              new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)); //上下文、自定义节点、传参
            try {
              promptAction.openCustomDialog(contentNode);
            } catch (error) {
              let message = (error as BusinessError).message;
              let code = (error as BusinessError).code;
              console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
            }
          })
      }
      .width('100%')
      .height('100%')
    }
    .height('100%')
  }
}

样式二:由下往上的方式弹出

效果图.

0030086000558681258.20240709173323.20147959015964841824469700767434.gif

方案

在自定义组件Builder里添加组件内转场动画(transition),设置组件转场时的平移效果和纵向的平移距离。

核心代码

@Builder
function buildText(params: Params) {
  Row(){
    Column() {
      Text(params.text)
        .fontSize(20)
        .textAlign(TextAlign.Center)
        .fontWeight(FontWeight.Bold)
        .padding(8)
      Text('方便为你提供本地新闻和天气信息,并且根据您的位置信息发现附近的免费WiFi')
        .fontSize(16)
        .textAlign(TextAlign.Center)
        .padding({ left:14,right:14})
        .margin({top:-4})
      Row({space:64}){
        Button("不允许")
        Button("允许")
      }
      .padding(24)
    }
    .width("90%")
    .borderRadius(8)
    .backgroundColor('#FFF0F0F0')
  }
  .height("100%")
  .visibility(800)
  // 定义进场出场转场动画效果
  .transition(TransitionEffect.OPACITY.animation({duration: 800}).combine(TransitionEffect.translate({y: 100})))
} //自定义组件的内容

写在最后

有很多小伙伴不知道学习哪些鸿蒙开发技术?不知道需要重点掌握哪些鸿蒙应用开发知识点?而且学习时频繁踩坑,最终浪费大量时间。所以有一份实用的鸿蒙(HarmonyOS NEXT)文档用来跟着学习是非常有必要的。

希望这一份鸿蒙学习文档能够给大家带来帮助,有需要的小伙伴自行领取,限时开源,先到先得~无套路领取!!

如果你是一名有经验的资深Android移动开发、Java开发、前端开发、对鸿蒙感兴趣以及转行人员,可以直接领取这份资料

请点击→纯血版全套鸿蒙HarmonyOS学习文档

鸿蒙(HarmonyOS NEXT)5.0最新学习路线

在这里插入图片描述

路线图适合人群:

IT开发人员:想要拓展职业边界
零基础小白:鸿蒙爱好者,希望从0到1学习,增加一项技能。
技术提升/进阶跳槽:发展瓶颈期,提升职场竞争力,快速掌握鸿蒙技术

获取以上完整版高清学习路线,请点击→纯血版全套鸿蒙HarmonyOS学习文档

《鸿蒙 (HarmonyOS)开发入门教学视频》

在这里插入图片描述

《鸿蒙生态应用开发V3.0白皮书》

在这里插入图片描述

《鸿蒙 (OpenHarmony)开发基础到实战手册》

OpenHarmony北向、南向开发环境搭建

在这里插入图片描述

《鸿蒙开发基础》

●ArkTS语言
●安装DevEco Studio
●运用你的第一个ArkTS应用
●ArkUI声明式UI开发
.……
在这里插入图片描述

《鸿蒙开发进阶》

●Stage模型入门
●网络管理
●数据管理
●电话服务
●分布式应用开发
●通知与窗口管理
●多媒体技术
●安全技能
●任务管理
●WebGL
●国际化开发
●应用测试
●DFX面向未来设计
●鸿蒙系统移植和裁剪定制
……
在这里插入图片描述

《鸿蒙进阶实战》

●ArkTS实践
●UIAbility应用
●网络案例
……
在这里插入图片描述

获取以上完整鸿蒙HarmonyOS学习文档,请点击→纯血版全套鸿蒙HarmonyOS学习文档

在这里插入图片描述

  • 13
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值