在非activity中使用alertDialog对话框

  有的时候,我们可能在activity类中调用非activity类中的方法,并需要在非activity类方法中定义AlertDialog对话框,怎么办呢:

 1.一般情况是在activity类中定义AlertDialog,如下代码;

  new AlertDialog.Builder(self) 
	  	.setTitle("确认")
	  	.setMessage("确定吗?")
	  	.setPositiveButton("是", null)
	  	.setNegativeButton("否", null)
	  	.show();
 2.在非 activity类中定义AlertDialog:

    DownLoadAPK.downLoad(getBaseContext());//activity类中

   

    public static void downLoad(Context context){//非<font size="4"><code><font size="4"><font size="4"><code><font size="4"><span style="font-size:18px;"><code><span style="font-size:18px;"><span style="font-size:18px;"><code>activity类中</code></span></span></code></span></font></code></font></font></code></font>
		System.out.println("context : " + context);
		new AlertDialog.Builder(context) 
	  	.setTitle("确认")
	  	.setMessage("确定吗?")
	  	.setPositiveButton("是", null)
	  	.setNegativeButton("否", null)
	  	.show();
	}
   这个时候会报错: Unable to add window -- token null is not for an application

  

  因此我们必须写成如下形式才正确

  DownLoadAPK.downLoad(<span style="color:#009900;">GetCategoryApkList.this</span>);//<span style="font-size:18px;"><code></code></span>GetCategoryApkList<font size="4">为<font size="4"><code><font size="4"><font size="4"><code><font size="4"><span style="font-size:18px;"><code><span style="font-size:18px;"><span style="font-size:18px;"><code>activity</code></span></span></code></span></font></code></font></font></code></font>类名
<code>  </code></font><pre name="code" class="java">  public static void downLoad(Context context){//非activity类中
		System.out.println("context : " + context);
		new AlertDialog.Builder(context) 
	  	.setTitle("确认")
	  	.setMessage("确定吗?")
	  	.setPositiveButton("是", null)
	  	.setNegativeButton("否", null)
	  	.show();
	}

 



    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值