Androidの android.view.WindowManager$BadTokenException: Unable to add window -- token null is not ...

异常案例

项目中使用BottomSheetDialogFragment作为底部弹框,出现异常:

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:1003)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:387)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:96)
        at android.app.Dialog.show(Dialog.java:344)
        at androidx.fragment.app.DialogFragment.onStart(DialogFragment.java:436)
        at com.steampy.app.activity.chat.messageitem.MessageItemNewDialog.onStart(MessageItemNewDialog.java:119)
        at androidx.fragment.app.Fragment.performStart(Fragment.java:2477)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1494)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
        at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)

异常多见于Diglog组件的使用中抛出。

@Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        if (getActivity() == null) {
            return super.onCreateDialog(savedInstanceState);
        }
        return new BottomSheetDialog(getApplicationContext(),R.style.TransparentBottomSheetStyle); //这里必须getActivity
    }

这里不能用getApplicationContext()

原因

导致报这个错是在于new BottomSheetDialog(mcontext),虽然这里的参数是BottomSheetDialog(Context context),但我们不能使用getApplicationContext()获得的Context,而必须使用Activity,因为只有一个Activity才能添加一个窗体。

解决方法

将new BottomSheetDialog(Context context)中的参数用 Activity.this(Activity是你的Activity的名称)或者getActivity()来填充就可以正确的创建一个Dialog了。

-同样的异常也经常出现在AlertDialog等弹框出现,都要传递ativity参数.

你可能感兴趣的:(Androidの android.view.WindowManager$BadTokenException: Unable to add window -- token null is not ...)