zoukankan      html  css  js  c++  java
  • android.view.WindowManager$BadTokenException: Unable to add window

    这是在加载dialog时出现的一个异常。转载地址:http://hi.baidu.com/fbdfp/item/7dea2d0ade9121813d42e23d

    扔了好久的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。
    

      

  • 相关阅读:
    洛谷 P1781 宇宙总统
    洛谷 P2524 Uim的情人节礼物·其之弐(康拓展开)
    洛谷 P1123 取数游戏
    洛谷 P4147 玉蟾宫 & P1169 [ZJOI2007]棋盘制作(求最大子矩阵)
    洛谷 P1387 最大正方形 & P2701 [USACO5.3]巨大的牛棚Big Barn (求最大子正方形)
    洛谷 P1464 Function
    洛谷 P1217 [USACO1.5]回文质数 Prime Palindromes
    洛谷 P1160 队列安排
    洛谷 P1451 求细胞数量
    洛谷 P1914 小书童——密码
  • 原文地址:https://www.cnblogs.com/tony-yang-flutter/p/3792890.html
Copyright © 2011-2022 走看看