HarmonyOS:固定样式弹出框

一、简介

固定样式弹出框采用固定的布局格式,这使得开发者无需关心具体的显示布局细节,只需输入所需显示的文本内容,从而简化了使用流程,提升了便捷性。

二、使用约束

  • 可以通过调用UIContext或getUIContext,在非UI页面或某些异步回调中使用本文中的接口。CalendarPickerDialog当前不支持此操作。
  • 操作菜单 (showActionMenu)、对话框 (showDialog)需先使用UIContext中的 getPromptAction() 方法获取到PromptAction对象,再通过该对象调用对应方法。
  • 列表选择弹出框 (ActionSheet)、警告弹出框 (AlertDialog)、选择器弹出框 (PickerDialog)中除CalendarPickerDialog都需先使用ohos.window中的 getUIContext() 方法获取UIContext实例,再通过此实例调用对应方法。或者可以通过自定义组件内置方法getUIContext()获取。
    操作菜单 (showActionMenu)、对话框 (showDialog)、列表选择弹出框 (ActionSheet)、警告弹出框 (AlertDialog)可以设置isModal为false变成非模态弹窗。
    操作菜单 (showActionMenu)、对话框 (showDialog)、列表选择弹出框 (ActionSheet)和警告弹出框 (AlertDialog)不支持设置内容区的字体样式,如字体颜色、大小换行等操作,如需自定义样式,建议使用不依赖UI组件的全局自定义弹出框或者基础自定义弹出框。

三、生命周期

弹出框提供了生命周期函数,用于通知用户该弹出框的生命周期。生命周期的触发时序依次为:onWillAppear -> onDidAppear -> onWillDisappear -> onDidDisappear,也可参照各组件API。
从API version 19开始,对话框(showDialog)、列表选择弹出框(ActionSheet)、警告弹出框(AlertDialog)支持以下生命周期。

名称 类型 说明
onWillAppear Callback 弹出框显示动效前的事件回调。
onDidAppear Callback 弹出框弹出后的事件回调。
onWillDisappear Callback 弹出框退出动效前的事件回调。
onDidDisappear Callback 弹出框消失后的事件回调。

四、操作菜单 (showActionMenu)

操作菜单通过UIContext中的getPromptAction方法获取到PromptAction对象,再通过该对象调用showActionMenu接口实现,支持在回调或开发者自定义类中使用。

操作菜单中,title字段的字体最大放大倍数为2。

创建并显示操作菜单后,菜单的响应结果会异步返回选中按钮在buttons数组中的索引。
效果图

示例代码

bash 复制代码
import { PromptAction } from '@kit.ArkUI';

@Entry
@Component
struct TestComponentDialog {
  promptAction: PromptAction = this.getUIContext().getPromptAction();

  showActionMenu() {// 操作菜单
    this.promptAction.showActionMenu({
      title: 'showActionMenu Title Info',
      buttons: [
        {
          text: '牛肉',
          color: '#000000'
        },
        {
          text: '三文鱼',
          color: '#000000'
        },
        {
          text: '带鱼',
          color: '#000000'
        },
        {
          text: '鸡蛋',
          color: '#000000'
        },
      ]
    })
      .then(data => {
        console.info('showActionMenu success, click button: ' + data.index);
      })
      .catch((err: Error) => {
        console.error('showActionMenu error: ' + err);
      })
  }

  build() {
    Column({ space: 30 }) {
      Button("showActionMenu")
        .onClick(() => {
          this.showActionMenu()
        })
    }
    .height('100%')
    .width('100%')
    .justifyContent(FlexAlign.Center)
  }
}

五、对话框 (showDialog)

对话框通过UIContext中的getPromptAction方法获取到PromptAction对象,再通过该对象调用showDialog接口实现,支持在回调或开发者自定义类中使用。

对话框中,title字段的字体最大放大倍数为2。

创建并显示对话框,对话框响应后异步返回选中按钮在buttons数组中的索引。
效果图

示例代码

bash 复制代码
import { PromptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';


@Entry
@Component
struct TestComponentDialog {
  promptAction: PromptAction = this.getUIContext().getPromptAction();

  showActionMenu() { // 操作菜单
    this.promptAction.showActionMenu({
      title: 'showActionMenu Title Info',
      buttons: [
        {
          text: '牛肉',
          color: '#000000'
        },
        {
          text: '三文鱼',
          color: '#000000'
        },
        {
          text: '带鱼',
          color: '#000000'
        },
        {
          text: '鸡蛋',
          color: '#000000'
        },
      ]
    })
      .then(data => {
        console.info('showActionMenu success, click button: ' + data.index);
      })
      .catch((err: Error) => {
        console.error('showActionMenu error: ' + err);
      })
  }

  showDialog(){// 对话框 (showDialog)
    try {
      this.promptAction.showDialog({
        title: 'showDialog Title Info',
        message: 'Message Info',
        buttons: [
          {
            text: 'button1',
            color: '#000000'
          },
          {
            text: 'button2',
            color: '#000000'
          }
        ]
      }, (err, data) => {
        if (err) {
          console.error('showDialog err: ' + err);
          return;
        }
        console.info('showDialog success callback, click button: ' + data.index);
      });
    } catch (error) {
      let message = (error as BusinessError).message;
      let code = (error as BusinessError).code;
      console.error(`showDialog args error code is ${code}, message is ${message}`);
    };
  }

  build() {
    Column({ space: 30 }) {
      Button("showActionMenu")
        .onClick(() => {
          this.showActionMenu()
        })
      Button("showDialog")
        .onClick(() => {
          this.showDialog()
        })
    }
    .height('100%')
    .width('100%')
    .justifyContent(FlexAlign.Center)
  }
}

六、选择器弹窗 (PickerDialog)

选择器弹窗通常用于在用户进行某些操作(如点击按钮)时显示特定的信息或选项。

6.1 日历选择器弹窗 (CalendarPickerDialog)

日历选择器弹窗提供日历视图,包含年、月和星期信息,通过CalendarPickerDialog 接口实现。开发者可调用show函数,定义并弹出日历选择器弹窗。

日历选择器弹窗的弹出依赖UI的执行上下文,不可在UI上下文不明确 的地方使用,具体约束参见UIContext说明。

通过配置 acceptButtonStyle、cancelButtonStyle可以实现自定义按钮样式。
效果图

示例代码

bash 复制代码
import { PromptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';


@Entry
@Component
struct TestComponentDialog {
  promptAction: PromptAction = this.getUIContext().getPromptAction();
  private selectedDate: Date = new Date('2025-09-28');

  showActionMenu() { // 操作菜单
    this.promptAction.showActionMenu({
      title: 'showActionMenu Title Info',
      buttons: [
        {
          text: '牛肉',
          color: '#000000'
        },
        {
          text: '三文鱼',
          color: '#000000'
        },
        {
          text: '带鱼',
          color: '#000000'
        },
        {
          text: '鸡蛋',
          color: '#000000'
        },
      ]
    })
      .then(data => {
        console.info('showActionMenu success, click button: ' + data.index);
      })
      .catch((err: Error) => {
        console.error('showActionMenu error: ' + err);
      })
  }

  showDialog(){// 对话框 (showDialog)
    try {
      this.promptAction.showDialog({
        title: 'showDialog Title Info',
        message: 'Message Info',
        buttons: [
          {
            text: 'button1',
            color: '#000000'
          },
          {
            text: 'button2',
            color: '#000000'
          }
        ]
      }, (err, data) => {
        if (err) {
          console.error('showDialog err: ' + err);
          return;
        }
        console.info('showDialog success callback, click button: ' + data.index);
      });
    } catch (error) {
      let message = (error as BusinessError).message;
      let code = (error as BusinessError).code;
      console.error(`showDialog args error code is ${code}, message is ${message}`);
    };
  }

  showCalendarPickerDialog(){
    CalendarPickerDialog.show({
      selected: this.selectedDate,
      acceptButtonStyle: {
        fontColor: '#2787d9',
        fontSize: '16fp',
        backgroundColor: '#f7f7f7',
        borderRadius: 10
      },
      cancelButtonStyle: {
        fontColor: Color.Red,
        fontSize: '16fp',
        backgroundColor: '#f7f7f7',
        borderRadius: 10
      },
      onAccept: (date: Date)=>{
        // 当弹出框再次弹出时显示选中的是上一次确定的日期
        this.selectedDate = date;
        console.log("选择的日期:",date.toDateString());
      }
    })
  }

  build() {
    Column({ space: 30 }) {
      Button("showActionMenu")
        .onClick(() => {
          this.showActionMenu()
        })
      Button("showDialog")
        .onClick(() => {
          this.showDialog()
        })
      Button("showCalendarPickerDialog")
        .onClick(() => {
          this.showCalendarPickerDialog()
        })
    }
    .height('100%')
    .width('100%')
    .justifyContent(FlexAlign.Center)
  }
}
6.2、日期滑动选择器弹窗 (DatePickerDialog)

开发者可以利用指定的日期范围,创建日期滑动选择器弹窗,将日期信息清晰地展示在弹出的窗口上。

日期滑动选择器弹窗通过UIContext中的showDatePickerDialog接口实现。

弹窗中配置lunarSwitch、showTime为true时,会展示切换农历的开关和时间,当checkbox被选中时,会显示农历。当按下确定按钮时,弹窗会通过onDateAccept返回目前所选中的日期。如需弹窗再次弹出时显示选中的是上一次确定的日期,就要在回调中重新给selectTime进行赋值。
效果图

示例代码

bash 复制代码
import { PromptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';


@Entry
@Component
struct TestComponentDialog {
  promptAction: PromptAction = this.getUIContext().getPromptAction();
  private selectedDate: Date = new Date('2025-09-28');

  showActionMenu() { // 操作菜单
    this.promptAction.showActionMenu({
      title: 'showActionMenu Title Info',
      buttons: [
        {
          text: '牛肉',
          color: '#000000'
        },
        {
          text: '三文鱼',
          color: '#000000'
        },
        {
          text: '带鱼',
          color: '#000000'
        },
        {
          text: '鸡蛋',
          color: '#000000'
        },
      ]
    })
      .then(data => {
        console.info('showActionMenu success, click button: ' + data.index);
      })
      .catch((err: Error) => {
        console.error('showActionMenu error: ' + err);
      })
  }

  showDialog() { // 对话框 (showDialog)
    try {
      this.promptAction.showDialog({
        title: 'showDialog Title Info',
        message: 'Message Info',
        buttons: [
          {
            text: 'button1',
            color: '#000000'
          },
          {
            text: 'button2',
            color: '#000000'
          }
        ]
      }, (err, data) => {
        if (err) {
          console.error('showDialog err: ' + err);
          return;
        }
        console.info('showDialog success callback, click button: ' + data.index);
      });
    } catch (error) {
      let message = (error as BusinessError).message;
      let code = (error as BusinessError).code;
      console.error(`showDialog args error code is ${code}, message is ${message}`);
    }
    ;
  }

  showCalendarPickerDialog() {
    CalendarPickerDialog.show({
      selected: this.selectedDate,
      acceptButtonStyle: {
        fontColor: '#2787d9',
        fontSize: '16fp',
        backgroundColor: '#f7f7f7',
        borderRadius: 10
      },
      cancelButtonStyle: {
        fontColor: Color.Red,
        fontSize: '16fp',
        backgroundColor: '#f7f7f7',
        borderRadius: 10
      },
      onAccept: (date: Date) => {
        // 当弹出框再次弹出时显示选中的是上一次确定的日期
        this.selectedDate = date;
        console.log("选择的日期:", date.toDateString());
      }
    })
  }

  @State selectTime: Date = new Date('2023-12-25T08:30:00');

  showDatePickerDialog() {
    this.getUIContext().showDatePickerDialog({
      start: new Date("2000-1-1"),
      end: new Date("2100-12-31"),
      selected: this.selectTime,
      lunarSwitch: true,
      showTime: true,
      onDateAccept: (value: Date) => {
        this.selectTime = value;
        console.info("选择的时间 DatePickerDialog:onAccept()" + JSON.stringify(value));
      },
    });
  }

  // 该示例通过配置disappearTextStyle、textStyle、selectedTextStyle、acceptButtonStyle、cancelButtonStyle实现了自定义文本以及按钮样式。
  showDatePickerDialog2() {
    this.getUIContext().showDatePickerDialog({
      start: new Date("2000-1-1"),
      end: new Date("2100-12-31"),
      selected: this.selectTime,
      textStyle: { color: '#2787d9', font: { size: '14fp', weight: FontWeight.Normal } },
      selectedTextStyle: { color: '#004aaf', font: { size: '18fp', weight: FontWeight.Regular } },
      acceptButtonStyle: {
        fontColor: '#2787d9',
        fontSize: '16fp',
        backgroundColor: '#f7f7f7',
        borderRadius: 10
      },
      cancelButtonStyle: {
        fontColor: Color.Red,
        fontSize: '16fp',
        backgroundColor: '#f7f7f7',
        borderRadius: 10
      }
    })
  }

  build() {
    Column({ space: 30 }) {
      Button("showActionMenu")
        .onClick(() => {
          this.showActionMenu()
        })
      Button("showDialog")
        .onClick(() => {
          this.showDialog()
        })
      Button("showCalendarPickerDialog")
        .onClick(() => {
          this.showCalendarPickerDialog()
        })
      Button("showDatePickerDialog")
        .onClick(() => {
          this.showDatePickerDialog()
        })
      Button("showDatePickerDialog2")
        .onClick(() => {
          this.showDatePickerDialog2()
        })
    }
    .height('100%')
    .width('100%')
    .justifyContent(FlexAlign.Center)
  }
}

该示例通过配置disappearTextStyle、textStyle、selectedTextStyle、acceptButtonStyle、cancelButtonStyle实现了自定义文本以及按钮样式。
效果图

示例代码

bash 复制代码
showDatePickerDialog2() {
    this.getUIContext().showDatePickerDialog({
      start: new Date("2000-1-1"),
      end: new Date("2100-12-31"),
      selected: this.selectTime,
      textStyle: { color: '#2787d9', font: { size: '14fp', weight: FontWeight.Normal } },
      selectedTextStyle: { color: '#004aaf', font: { size: '18fp', weight: FontWeight.Regular } },
      acceptButtonStyle: {
        fontColor: '#2787d9',
        fontSize: '16fp',
        backgroundColor: '#f7f7f7',
        borderRadius: 10
      },
      cancelButtonStyle: {
        fontColor: Color.Red,
        fontSize: '16fp',
        backgroundColor: '#f7f7f7',
        borderRadius: 10
      }
    })
6.3 时间滑动选择器弹窗 (TimePickerDialog)

开发者可根据24小时的时间区间,创建时间滑动选择器弹窗,将时间信息清晰地展示在弹出的窗口上。

时间滑动选择器弹窗通过UIContext中的showTimePickerDialog 接口实现。

该示例通过配置disappearTextStyle、textStyle、selectedTextStyle、acceptButtonStyle、cancelButtonStyle实现了自定义文本以及按钮样式。
效果图

示例代码

bash 复制代码
 @State selectTime3: Date = new Date('2025-09-29T08:30:00');
  showTimePickerDialog(){// 时间滑动选择器弹窗 (TimePickerDialog)
    this.getUIContext().showTimePickerDialog({
      selected: this.selectTime3,
      textStyle: { color: '#2787d9', font: { size: '14fp', weight: FontWeight.Normal } },
      selectedTextStyle: { color: '#004aaf', font: { size: '18fp', weight: FontWeight.Regular } },
      acceptButtonStyle: {
        fontColor: '#2787d9',
        fontSize: '16fp',
        backgroundColor: '#f7f7f7',
        borderRadius: 10
      },
      cancelButtonStyle: {
        fontColor: Color.Red,
        fontSize: '16fp',
        backgroundColor: '#f7f7f7',
        borderRadius: 10
      }
    });
  }
6.4 文本滑动选择器弹窗 (TextPickerDialog)

开发者可根据指定的选择范围,创建文本滑动选择器弹窗,将文本信息清晰地展示在弹出的窗口上。

文本滑动选择器弹窗通过UIContext中的showTextPickerDialog 接口实现。

该示例通过设置range的参数类型为TextCascadePickerRangeContent[],实现3列文本选择器弹窗。当按下确定按钮时,弹窗会通过onAccept返回目前所选中文本和索引值。如需弹窗再次弹出时显示选中的是上一次确定的文本,就要在回调中重新给select进行赋值。
效果图

示例代码

bash 复制代码
 private cityArray: TextCascadePickerRangeContent[] = [
    {
      text: '上海市',
      children: [{
        text: '上海市',
        children: [{ text: '浦东新区' }, { text: '黄浦区' }, { text: '宝山区' }, { text: '长宁区' }, { text: '嘉定区' },
          { text: '青浦区' }, { text: '虹口区' }]
      }]
    },
    {
      text: '辽宁省',
      children: [{ text: '沈阳市', children: [{ text: '沈河区' }, { text: '和平区' }, { text: '浑南区' }] },
        { text: '大连市', children: [{ text: '中山区' }, { text: '金州区' }, { text: '长海县' }] }]
    },
    {
      text: '吉林省',
      children: [{ text: '长春市', children: [{ text: '南关区' }, { text: '宽城区' }, { text: '朝阳区' }] },
        { text: '四平市', children: [{ text: '铁西区' }, { text: '铁东区' }, { text: '梨树县' }] }]
    },
    {
      text: '黑龙江省',
      children: [{ text: '哈尔滨市', children: [{ text: '道里区' }, { text: '道外区' }, { text: '南岗区' }] },
        { text: '牡丹江市', children: [{ text: '东安区' }, { text: '西安区' }, { text: '爱民区' }] }]
    }
  ];
  private select: number = 0;

  showTextPickerDialog() {
    this.getUIContext().showTextPickerDialog({
      range: this.cityArray,
      selected: this.select,
      onAccept: (value: TextPickerResult) => {
        this.select = value.index as number
        console.log("已选择的城市: ", JSON.stringify(value))
      }
    });
  }
6.4 列表选择弹窗 (ActionSheet)

列表选择器弹窗适用于呈现多个操作选项,尤其当界面中仅需展示操作列表而无其他内容时。

列表选择器弹窗通过UIContext中的showActionSheet 接口实现。

列表选择弹窗中,title字段的字体最大放大倍数为2。

该示例通过配置width、height、transition等接口,定义了弹窗的样式以及弹出动效。
效果图

示例代码

bash 复制代码
showActionSheet() { // 列表选择弹窗 (ActionSheet)
    this.getUIContext().showActionSheet({
      title: 'ActionSheet title',
      message: 'message',
      autoCancel: false,
      width: 300,
      height: 300,
      cornerRadius: 20,
      borderWidth: 1,
      borderStyle: BorderStyle.Solid,
      borderColor: Color.Blue,
      backgroundColor: Color.White,
      transition: TransitionEffect.asymmetric(TransitionEffect.OPACITY
        .animation({ duration: 3000, curve: Curve.Sharp })
        .combine(TransitionEffect.scale({ x: 1.5, y: 1.5 }).animation({ duration: 3000, curve: Curve.Sharp })),
        TransitionEffect.OPACITY.animation({ duration: 100, curve: Curve.Smooth })
          .combine(TransitionEffect.scale({ x: 0.5, y: 0.5 }).animation({ duration: 100, curve: Curve.Smooth }))),
      confirm: {
        value: 'Confirm button',
        action: () => {
          console.info('Get Alert Dialog handled');
        }
      },
      alignment: DialogAlignment.Center,
      sheets: [
        {
          title: '蓝莓',
          action: () => {
            console.info('选择了 蓝莓');
          }
        },
        {
          title: '苹果',
          action: () => {
            console.info('选择了 苹果');
          }
        },
        {
          title: '香蕉',
          action: () => {
            console.info('选择了 香蕉');
          }
        },
        {
          title: '梨',
          action: () => {
            console.info('选择了 梨');
          }
        }
      ]
    });
  }
相关推荐
Devil枫9 小时前
HarmonyOS 广告服务 ArkTS 实现指南:从激励广告到多形式适配
华为·harmonyos
猫林老师13 小时前
HarmonyOS 5 性能优化全攻略:从启动加速到内存管理
华为·性能优化·harmonyos
猫林老师14 小时前
HarmonyOS 5 手势系统与高级交互动效开发实战
华为·交互·harmonyos
chensi_0715 小时前
uniapp x 鸿蒙开发之调试证书签名配置
服务器·uni-app·harmonyos
搬砖的小码农_Sky17 小时前
鸿蒙(HarmonyOS)应用开发技能栈
harmonyos·鸿蒙系统
D.....l19 小时前
Hi3861 OpenHarmony鸿蒙开发(嵌入式方向) (一)
华为·harmonyos
无风听海1 天前
HarmonyOS之 @Provide 装饰器实现跨组件双向状态同步
华为·harmonyos
安卓开发者1 天前
鸿蒙NEXT传统蓝牙开发指南:从基础到实战的完整解决方案
harmonyos
代码79721 天前
使用会话存储时,处理存储信息加密问题
深度学习·算法·自动化·散列表·harmonyos