ApplicationContext AlertDialog IllegalStateException: You need to use a Theme.AppCompat theme

本文介绍了解决在使用AlertDialog时出现的IllegalStateException异常的方法。通过正确设置主题样式和使用两参数构造函数,可以在非Activity环境下成功创建并显示弹窗对话框。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

new AlertDialog.Builder(context)

创建AlertDialog时, Context如果用Activity不会有任何问题, 如果用Application会抛出上面的异常.

解决方法如下:

Builder使用两参的构造器, Builder(@NonNull Context context, @StyleRes int themeResId)

new AlertDialog.Builder(getApplicationContext, android.support.v7.appcompat.R.style.Theme_AppCompat_Light_Dialog_Alert)

第二个参数需要传一个style进去, 比如上面那个

不在Activity里面的弹窗只能用系统级别的弹窗. 需要申请权限

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext, 
android.support.v7.appcompat.R.style.Theme_AppCompat_Light_Dialog_Alert);
   builder.setTitle("Title");
   ......
   AlertDialog alertDialog = builder.create();
   //需要声明 android.permission.SYSTEM_ALERT_WINDOW权限
   alertDialog.getWindow().setType(LayoutParams.TYPE_SYSTEM_ALERT);
   alertDialog.show();

有些Rom需要手动打开悬浮窗权限, 可以引导到开启页面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值