天天看點

Set Positive|Neutral|Negative Button disabled in AlertDialog

今天設定AlertDialog的按鈕不可用,一直出現空指針異常,看來看去代碼也挺正常啊,AlertDialog.Builder.create(),之後調用

dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);  

I get another trouble with it. I'm trying to retrieve this button on onCreateDialog(...) method, I always get nullPointerException by using

(AlertDialog)dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);   

Before or after:

dialog=builder.create()  

 原來必須在dialog.show()之後,才能用

dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);   

否則即便是在create方法之後,擷取到的Button仍然是空的,于是就看了一下API:

Creates a AlertDialog with the arguments supplied to this builder. It does not show() the dialog. This allows the user to do any extra processing before displaying the dialog. Use show() if you don't have any other processing to do and want this to be created and displayed.   

按我的了解, 就是說在Show(Display)這個對話框之前,即便已經調用create方法,它的狀态是不确定的,可以做任何處理,這時候就不能擷取到對話框的Button及其他元素。

本文轉自 breezy_yuan 51CTO部落格,原文連結:http://blog.51cto.com/lbrant/429518,如需轉載請自行聯系原作者

繼續閱讀