[Android] Context應該怎麼寫?

來源:互聯網
上載者:User

如果想要彈出一個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);

然後就成功了

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.