onCreateDialog 时出错

在创建各种Dialog时,通过重写Activity其类的方法 protected Dialog onCreateDialog(int id) 来创建Dialog,在需要显示的地方调用showDialog(int id),显示即可。在其中创建Dialog时,总是失败,究其原因:[ERROR/AndroidRuntime(7716): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application]  AlertDialog.Builder build = new AlertDialog.Builder(getApplicationContext());这一句遇到问题,后改成 AlertDialog.Builder build = new AlertDialog.Builder(this);问题解决!

Context context = getApplicationContext();

Context context = **Activity.this;

其差别:

    

getApplicationContext()(SKD 文档):

     /**

     * Return the context of the single, global Application object of the
     * current process.  This generally should only be used if you need a
     * Context whose lifecycle is separate from the current context, that is
     * tied to the lifetime of the process rather than the current component.
     * 
     * <p>Consider for example how this interacts with
     * {@ #registerReceiver(BroadcastReceiver, IntentFilter)}:
     * <ul>
     * <li> <p>If used from an Activity context, the receiver is being registered
     * within that activity.  This means that you are expected to unregister
     * before the activity is done being destroyed; in fact if you do not do
     * so, the framework will clean up your leaked registration as it removes
     * the activity and log an error.  Thus, if you use the Activity context
     * to register a receiver that is static (global to the process, not
     * associated with an Activity instance) then that registration will be
     * removed on you at whatever point the activity you used is destroyed.
     * <li> <p>If used from the Context returned here, the receiver is being
     * registered with the global state associated with your application.  Thus
     * it will never be unregistered for you.  This is necessary if the receiver
     * is associated with static data, not a particular component.  However
     * using the ApplicationContext elsewhere can easily lead to serious leaks
     * if you forget to unregister, unbind, etc.


getApplicationContext() 生命周期是整个应用,应用摧毁它才摧毁
Activity.this的context属于activity ,activity 摧毁他就摧毁


因为只有一个Activity才能添加一个窗体。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值