如果在dialog對話框中添加一個按鈕,那么它對應的點擊事件應該回調View.OnClickListener()方法呢還是DialogInterface.OnClickListener()方法呢?
1 /* 創建對話框 */ 2 public void showdialog(String title, String message){ 3 AlertDialog.Builder builder = new Builder(this); 4 builder.setIcon(R.drawable.ic_launcher); 5 builder.setTitle(title); 6 builder.setMessage(message); 7 builder.setPositiveButton("確定", new DialogInterface.OnClickListener() { 8 9 @Override 10 public void onClick(DialogInterface dialog, int which) { 11 12 13 } 14 }); 15 builder.create().show(); 16 17 }
其實答案很簡單,看下setPositiveButton的關聯代碼:
1 /** 2 * Set a listener to be invoked when the positive button of the dialog is pressed. 3 * @param text The text to display in the positive button 4 * @param listener The {@link DialogInterface.OnClickListener} to use. 5 * 6 * @return This Builder object to allow for chaining of calls to set methods 7 */ 8 public Builder setPositiveButton(CharSequence text, final OnClickListener listener) { 9 P.mPositiveButtonText = text; 10 P.mPositiveButtonListener = listener; 11 return this; 12 }
O(∩_∩)O代碼中已經標注的很清楚了,這里的第二個param應該使用DialogInterface.OnClickListener,而針對View.OnClickListener和DialogInterface.OnClickListener的區別,來看看關聯代碼:
DialogInterface.OnClickListener
1 /** 2 * Interface used to allow the creator of a dialog to run some code when an 3 * item on the dialog is clicked.. 4 */ 5 interface OnClickListener { 6 /** 7 * This method will be invoked when a button in the dialog is clicked. 8 * 9 * @param dialog The dialog that received the click. 10 * @param which The button that was clicked (e.g. 11 * {@link DialogInterface#BUTTON1}) or the position 12 * of the item clicked. 13 */ 14 /* TODO: Change to use BUTTON_POSITIVE after API council */ 15 public void onClick(DialogInterface dialog, int which); 16 }
View.OnClickListener
1 /** 2 * Interface definition for a callback to be invoked when a view is clicked. 3 */ 4 public interface OnClickListener { 5 /** 6 * Called when a view has been clicked. 7 * 8 * @param v The view that was clicked. 9 */ 10 void onClick(View v); 11 }
喏,寫的很清楚了,一個是dialog中的button被clicked了調用,一個是View被clicked了回調。
理解這么多,后期再補充............