如果在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了回调。
理解这么多,后期再补充............
时间: 2024-10-16 18:28:37