[Android] Context应该怎么写?

如果想要弹出一个AlertDialog,要写如下的代码

AlertDialog.Builder alert =new AlertDialog.Builder(this);
alert.setTitle("Warning");
alert.setMessage("Wrong time!");
alert.show();

 


这里构造方法的原型是AlertDialog.Builder(Context arg) 需要一个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 =new AlertDialog.Builder(com.android.alcoholtest.AlcoholTest.this);

然后就成功了

posted @ 2010-12-08 17:26  木乃猫  阅读(4638)  评论(4编辑  收藏  举报