在HarmonyOS NEXT中 弹窗封装成一个方法在其他地方直接调用?

阅读 479
avatarAI BotBETA
### 回答

在HarmonyOS NEXT中,你可以将弹窗封装成一个方法,并在其他地方直接调用。以下是一个简单的示例,展示了如何实现这一点:

1. **创建一个弹窗方法**:

   你可以在一个工具类或UI类中创建一个静态或非静态方法来封装弹窗逻辑。例如:

public class DialogUtils {

   // 静态方法,用于显示一个简单的弹窗
   public static void showSimpleDialog(ComponentContext context) {
       CommonDialog dialog = new CommonDialog(context);
       dialog.setTitle("Title");
       dialog.setMessage("This is a simple dialog.");
       dialog.setCancelable(true);

       // 设置点击事件
       dialog.addAction(new CommonDialog.DialogAction(new Intent() {{
           setAction(CommonDialog.ACTION_POSITIVE_BUTTON_CLICKED);
       }}) {{
           setText("OK");
       }});

       dialog.addAction(new CommonDialog.DialogAction(new Intent() {{
           setAction(CommonDialog.ACTION_NEGATIVE_BUTTON_CLICKED);
       }}) {{
           setText("Cancel");
       }});

       dialog.show();
   }

}


2. **在其他地方调用该方法**:

在你的Activity或其他组件中,你可以直接调用这个方法来显示弹窗:

@Override
protected void onStart(Intent intent) {

   super.onStart(intent);
   super.setUIContent(ResourceTable.Layout_ability_main);

   // 显示弹窗
   DialogUtils.showSimpleDialog(this);

}


这样,你就成功地将弹窗封装成了一个方法,并可以在其他地方直接调用它来显示弹窗。
1 个回答

创建一个函数来封装 AlertDialog 的创建和显示逻辑。AlertDialog 常用于展示简单的提示信息、确认框等内容。

import { AlertDialog, Button, Text } from '@ohos.application.dialog';

// 封装显示简单提示弹窗的方法
function showSimpleAlert(message: string, title: string = "提示") {
    let dialog = new AlertDialog({
        title: title,
        message: message,
        buttons: [
            {
                text: "确定",
                onClick: () => {
                    dialog.destroy(); // 点击确定按钮后关闭弹窗
                }
            }
        ]
    });
    dialog.show();
}

本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进