HarmonyOS鸿蒙Next中如何定位AlertDialog样式失效问题

HarmonyOS鸿蒙Next中如何定位AlertDialog样式失效问题

【问题现象】

AlertDialog只显示了按钮文字,无颜色、边框等样式。如图:

点击放大

问题代码如下:

import router from '@ohos.router';
import { AlertDialog } from '@ohos.arkui.advanced.Dialog'

@Entry
@Component
struct Browser {
  @State showDialog: boolean = false;
  @State showButton: boolean = true;

  build() {
    Column() {
       Button("按钮")
          .width(60)
          .height(30)
          .onClick(() => {
          this.showDialog = true;
        });

        if (this.showDialog) {
          AlertDialog({
            primaryTitle: '提示',
            content: '是否确认返回主菜单?',
            primaryButton: {
              value: '取消',
              action: () => {
                this.showDialog = false;
              },
            },
            secondaryButton: {
              value: '确定',
              role: ButtonRole.ERROR,
              fontColor: Color.Blue,
              action: () => {
                this.showDialog = false;
                router.back();
              }
            },
          })
        }
      }.width('100%').height('100%');    
  }
}

【背景知识】

警告弹窗 (AlertDialog)

显示警告弹窗组件,可设置文本内容与响应回调。

【定位思路】

  1. 使用DevEco Studio自带的ArkUI Insector检查AlertDialog,发现AlertDialog元素的backgroundColor全是 #00000000 (十六进制对应的颜色为透明色),故需要设置背景色。

    如下图:按红色标号顺序即可查看到元素属性。

    点击放大

  2. 排查AlertDialog API,backgroundColor属性为非必填,默认为Color.Transparent透明色,即显示为父组件容器颜色。问题代码未设置颜色,故为父容器的默认白色。

    点击放大

  3. 通过以上步骤,确定问题根因为AlertDialog 默认背景色为透明色,需要主动设置颜色才能正常显示颜色。

【解决方案】

设置AlertDialog backgroundColor,以下为问题代码修改点:

AlertDialog({...})
 .backgroundColor(Color.Orange)
 .backgroundBlurStyle(BlurStyle.NONE) // 关闭背景虚化

修改后,能显示颜色效果:

点击放大

【总结】

AlertDialog默认背景颜色为Color.Transparent,且非必选,使用时需要注意设置背景色,否则显示为父组件颜色。


更多关于HarmonyOS鸿蒙Next中如何定位AlertDialog样式失效问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next中如何定位AlertDialog样式失效问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


问题根因

问题根因是AlertDialog默认背景色为透明色,未设置背景色导致样式失效。通过设置backgroundColor属性即可解决。修改代码如下:

AlertDialog({...})
  .backgroundColor(Color.Orange)
  .backgroundBlurStyle(BlurStyle.NONE) // 关闭背景虚化
回到顶部