【问题标题】:how to pop up an AlertDialog in Android Framework如何在 Android 框架中弹出 AlertDialog
【发布时间】:2022-10-18 14:42:13
【问题描述】:

我想在 Android 框架的某个地方弹出一个 AlertDialog,问题是需要一个 ui 上下文,而在框架的大多数部分中没有这样的 ui 上下文。

经过一番研究,我在 AutofillManagerService.java 中找到了一个示例: https://cs.android.com/android/platform/superproject/+/master:frameworks/base/services/autofill/java/com/android/server/autofill/AutofillManagerService.java;l=199?q=AutofillManage&ss=android%2Fplatform%2Fsuperproject

mUi = new AutoFillUI(ActivityThread.currentActivityThread().getSystemUiContext());

这里的 ui 上下文 (ActivityThread.currentActivityThread().getSystemUiContext()) 将被传递给 SaveUi 以创建一个对话框: https://cs.android.com/android/platform/superproject/+/master:frameworks/base/services/autofill/java/com/android/server/autofill/ui/SaveUi.java;l=340;bpv=0;bpt=1

        mDialog = new Dialog(context, mThemeId);
        mDialog.setContentView(view);

        // Dialog can be dismissed when touched outside, but the negative listener should not be
        // notified (hence the null argument).
        mDialog.setOnDismissListener((d) -> mListener.onCancel(null));

        final Window window = mDialog.getWindow();
        window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
        window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
                | WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        window.setDimAmount(0.6f);
        window.addPrivateFlags(WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER);
        window.setCloseOnTouchOutside(true);
        final WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.accessibilityTitle = context.getString(R.string.autofill_save_accessibility_title);
        params.windowAnimations = R.style.AutofillSaveAnimation;

        show();

但是,当我尝试做同样的事情时它崩溃了,我的代码类似于:

new AlertDialog.Builder(ActivityThread.currentActivityThread().getSystemUiContext())
                    .setTitle("some title")
                    .setMessage("some message")
                    .setPositiveButton("yes", (dialog, which) -> {
                    })
                    .setNegativeButton("no", (dialog, which) -> {
                    })
                    .create()
                    .show();

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 尝试从可以获得活动上下文的地方调用显示对话框。将此上下文作为参数注入。不要忘记检查活动isFinishing 与否。
  • 有没有办法使用ActivityThread.currentActivityThread().getSystemUiContext() 来实现这个目标,而不是引入一个活动上下文。
  • 不,这个ActivityThread 类对核心框架是隐藏的。所以,你不能。

标签: android


【解决方案1】:

在android中有很多获取上下文的方法。在活动中,您可以通过这个关键字,或者在片段中,它可能是要求上下文(),或者简单的是应用上下文.你试过这个吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    相关资源
    最近更新 更多