android.view.WindowManager$BadTokenException: Unable to add window
这是在加载dialog时出现的一个异常。转载地址:http://hi.baidu.com/fbdfp/item/7dea2d0ade9121813d42e23d
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 扔了好久的android又开始断断续续在接触。昨天不知道看了个什么东东之后就看到关于LayoutInflater的用法,于是想 try 一下,也就是在Button上点击一下弹出一个对话框,结果遇到一个问题,android.view.WindowManager$BadTokenException: Unable to add window 报了这个错。 private void showCustomDialog() { // TODO Auto-generated method stub AlertDialog.Builder builder; AlertDialog dialog; LayoutInflater inflator = (LayoutInflater) LayoutInflatorActivity. this .getSystemService(LAYOUT_INFLATER_SERVICE); View view = inflator.inflate(R.layout.dialoglayout, null ); TextView text = (TextView) view.findViewById(R.id.textview); ImageButton imageButton = (ImageButton) view.findViewById(R.id.imageButton); builder = new AlertDialog.Builder( this ); builder.setView(view); dialog = builder.create(); dialog.show(); } 在这句上报错了。因为本来我的写法是: builder = new AlertDialog.Builder( this .getApplicationContext()); 因为看了API 是 new AlertDialog.Builder(Context context);想着也没什么语法错误吧。 结果网上搜了一下,大概解释了一下获取上下文 this .getApplicationContext()); 和 this 的区别: 这里的 this 指的当然就是Acitivity. this , 指的是这个Acitivity的上下文,而 this .getApplicationContext()指的则是整个应用的上下文。 对于AlertDialog来说,是需要依赖一个View,而View是对应于Activity的。 那么为什么会报错呢,这里涉及到一个生命周期的问题了。 对于一个应用Context来说,它的生命周期是整个应用程序的生命周期,而对于Activity来说,当它销毁之后它的生命周期就结束了。 AlertDialog是属于Acitivity的,当Activity销毁的时候它也必须销毁,所以这里我们指定是Activity的Context。 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库