【Android Framework核心面试题】为什么Dialo

2023-09-22  本文已影响0人  小城哇哇

为什么Dialog不能用Application的Context?

详细讲解

享学课堂移动开发课程:Framework专题 WMS部分

这道题想考察什么?

  1. 是否了解Dialog的运行机制?

考察的知识点

  1. Window、WindowManager、WindowMangerService之间的关系
  2. Dialog使用Activity的Token的原因

考生应该如何回答

  1. 首先我们看一下如果用Application的Context出现什么状况?
 Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:907)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:387)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
        at android.app.Dialog.show(Dialog.java:342)
  1. Window、WM、WMS、Token的概念?
  1. Dialog的窗口属于什么类型?
  1. 来看下Dialog的构造方式
Dialog(@NonNull Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {
        if (createContextThemeWrapper) {
            if (themeResId == Resources.ID_NULL) {
                final TypedValue outValue = new TypedValue();
                context.getTheme().resolveAttribute(R.attr.dialogTheme, outValue, true);
                themeResId = outValue.resourceId;
            }
            mContext = new ContextThemeWrapper(context, themeResId);
        } else {
            mContext = context;
        }

        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        final Window w = new PhoneWindow(mContext);
        mWindow = w;
        w.setCallback(this);
        w.setOnWindowDismissedCallback(this);
        w.setOnWindowSwipeDismissedCallback(() -> {
            if (mCancelable) {
                cancel();
            }
        });
        w.setWindowManager(mWindowManager, null, null);
        w.setGravity(Gravity.CENTER);

        mListenersHandler = new ListenersHandler(this);
    }

最后

有需要面试题的朋友可以关注一下哇哇,以上都可以分享!!!

上一篇 下一篇

猜你喜欢

热点阅读