HarmonyOS鸿蒙Next中openCustomDialog平板适配

HarmonyOS鸿蒙Next中openCustomDialog平板适配 如何在平板竖屏时打开openCustomDialog弹窗宽度为60%,此时不关闭弹窗,平板旋转为横屏弹窗宽度变为40%。

3 回复

【背景知识】

由于CustomDialog在使用上存在诸多限制,不支持动态创建也不支持动态刷新,在相对较复杂的应用场景中推荐使用UIContext中获取到的PromptAction对象提供的openCustomDialog接口来实现自定义弹出框。

【解决方案】

由于ComponentContent不支持自定义组件使用@Reusable、@Link、@Provide、@Consume等装饰器,来同步弹出框弹出的页面与ComponentContent中自定义组件的状态。因此,若需要更新弹出框中自定义组件的内容可以通过ComponentContent提供的update方法来实现,更新弹出框的UI样式,示例代码如下:

import { ComponentContent } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

class Params {
  width: string = '60%'

  constructor(width: string) {
    this.width = width;
  }
}

@Entry
@Component
struct Index {
  build() {
    Row() {
      Column() {
        Button('open')
          .onClick(() => {
            let uiContext = this.getUIContext();
            let dialogContent = new ComponentContent(uiContext, wrapBuilder(buildText), new Params('60%'));
            uiContext.getPromptAction().openCustomDialog(dialogContent)
              .then(() => {
                console.info('OpenCustomDialog complete.');
              })
              .catch((error: BusinessError) => {
                console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`);
              })

            setTimeout(() => {
              dialogContent.update(new Params('40%'));
            }, 1000)

            setTimeout(() => {
              dialogContent.update(new Params('60%'));
            }, 2000)
          })
      }
    }
  }
}

@Builder
function buildText(params: Params) {
  Column() {
    Text(params.width)
      .fontSize(50)
      .fontWeight(FontWeight.Bold)
      .margin({ bottom: 36 })
  }.backgroundColor('#ffe28f8f')
  .width(params.width)
}

更多关于HarmonyOS鸿蒙Next中openCustomDialog平板适配的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,openCustomDialog的平板适配主要通过自适应布局能力实现。组件会根据平板屏幕尺寸自动调整弹窗大小和位置,开发者无需手动处理不同设备差异。使用ArkUICustomDialogController时,系统会自动优化显示效果,确保在平板上合理呈现。可设置dialogWidthdialogHeight属性为百分比值(如"50%")来适应平板屏幕。建议使用资源文件定义不同设备的尺寸参数,系统会自动匹配对应规格。

在HarmonyOS Next中实现平板旋转时动态调整openCustomDialog弹窗宽度,可以通过监听屏幕方向变化并动态更新弹窗样式来实现:

  1. 首先在自定义弹窗的Builder中设置初始宽度:
const dialogController = CustomDialogController({
    builder: CustomDialogView({
        width: isPortrait ? '60%' : '40%'
    }),
    // 其他配置...
});
  1. 使用屏幕方向监听器:
import window from '@ohos.window';

// 监听屏幕方向变化
window.on('windowOrientationChange', (orientation) => {
    if (dialogController.isOpen) {
        const isPortrait = orientation === window.Orientation.PORTRAIT;
        dialogController.updateProperties({
            width: isPortrait ? '60%' : '40%'
        });
    }
});
  1. 在自定义弹窗组件中处理布局更新:
@Component
struct CustomDialogView {
    @Prop width: string = '60%'

    build() {
        Column() {
            // 弹窗内容
        }
        .width(this.width)
        .height('...')
    }
}

注意:需要确保在页面销毁时取消监听,并处理好横竖屏切换时的动画效果。这种方式可以实现弹窗宽度随屏幕方向动态调整,同时保持弹窗处于打开状态。

回到顶部