每日一题:为什么Dialog不能用Application的Con

2023-06-28  本文已影响0人  代码我写的怎么

在android面试中,我们常会遇到Framework面试相关问题,而今天要分享的就是为什么Dialog不能用Application的Context?

其主要考察的是程序员是否了解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);
    }

今日分享到此结束,下期更精彩~

关注个人简介,面试不迷路~

上一篇 下一篇

猜你喜欢

热点阅读