Android Context应该如何写

AlertDialog构造详解
本文详细介绍了如何在Android应用中创建AlertDialog,并给出了具体的代码示例。针对自定义接口实现时出现的Context问题进行了探讨,最终通过正确指定Context解决了问题。

如果想要实现一个AlertDialog,我们需要写如下的代码 :

1. AlertDialog.Builder alert =new AlertDialog.Builder(this); 

2. alert.setTitle("Warning"); 

3. alert.setMessage("Wrong time!"); 

4. alert.show();

这里构造方法的原型是AlertDialog.Builder(Context context) 需要一个Context对象作为参数,一般情况下我们都是都在Activity里写,所以用this,表示在当前的会话中弹出AlertDialog。 在我的一个程序里,我自定义了一个接口Public interface CustomPickerListener,在实现这个接口的方法时我需要弹出来一个AlertDialog,这里,参数表里填写this的话会提示错误:The constructor AlertDialog.Builder(new CustomPickerListener(){}) is undefined. 其实这个地方写this很明显是错误的,但是要写什么才能达成目的呢? 官方文档上对context的解释是

Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

于是我就试着写上了我程序的 包.目标类.this ,如下

AlertDialog.Builder   alert =newAlertDialog.Builder(com.android.alcoholtest.AlcoholTest.this);

然后就成功了。

 

转载于:https://my.oschina.net/u/2971691/blog/817109

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值