如果想要彈出一個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);
然後就成功了