這裏節選了AlertController的源碼,它是AlertDialog.Builder中非常重要的工具類,主要作用是根據Builder中配置好的參數來生成對應的Dialog。
我節選下面這段代碼的原因就是因爲我們通過AlertDialog.Builder創建的dialog,只要點擊Positive、Negative、Neutral等按鈕就會觸發dismiss方法,然後自行關閉。。。雖然大家都知道點擊按鈕之後會觸發dismiss,但是估計很少有人知道dismiss方法是通過什麼方式觸發的吧。。。所以我這波源碼追蹤,也算是溯源找真相了
另外安利一個查詢Android源碼的網站--->Android源碼
private final View.OnClickListener mButtonHandler = new View.OnClickListener() {
@Override
public void onClick(View v) {
final Message m;
if (v == mButtonPositive && mButtonPositiveMessage != null) {
m = Message.obtain(mButtonPositiveMessage);
} else if (v == mButtonNegative && mButtonNegativeMessage != null) {
m = Message.obtain(mButtonNegativeMessage);
} else if (v == mButtonNeutral && mButtonNeutralMessage != null) {
m = Message.obtain(mButtonNeutralMessage);
} else {
m = null;
}
if (m != null) {
m.sendToTarget();
}
// Post a message so we dismiss after the above handlers are executed
mHandler.obtainMessage(ButtonHandler.MSG_DISMISS_DIALOG, mDialogInterface)
.sendToTarget();
}
};
private static final class ButtonHandler extends Handler {
// Button clicks have Message.what as the BUTTON{1,2,3} constant
private static final int MSG_DISMISS_DIALOG = 1;
private WeakReference<DialogInterface> mDialog;
public ButtonHandler(DialogInterface dialog) {
mDialog = new WeakReference<DialogInterface>(dialog);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DialogInterface.BUTTON_POSITIVE:
case DialogInterface.BUTTON_NEGATIVE:
case DialogInterface.BUTTON_NEUTRAL:
((DialogInterface.OnClickListener) msg.obj).onClick(mDialog.get(), msg.what);
break;
case MSG_DISMISS_DIALOG:
//這裏調用了dismiss方法
((DialogInterface) msg.obj).dismiss();
}
}
}