Distinguish individual dialogs using DialogInterface.OnClickListener

We have two AlertDialog

 AlertDialog dialog1, dialog2; 

both dialogs are created using AlertDialog.Builder .
How do I know which dialog is the source of an event in DialogInterface.OnClickListener ?

with one dialog we can do this:

 AlertDialogInstance.setOnClickListener(myListener); //myListener public void onClick(DialogInterface arg0, int arg1) { switch (arg1) { case AlertDialog.BUTTON_NEGATIVE: // do something break; case AlertDialog.BUTTON_POSITIVE: // do something break; case AlertDialog.BUTTON_NEUTRAL: // do something break; } } 

how to change this switch logic to handle multiple dialogs?
(Or, if there is a more efficient system for handling dialogs, besides callbacks of built-in buttons, what is it?)

+6
source share
3 answers

I will recommend that you put the required parameter in a user listener.

 private class CustomOnClickListener implements OnClickListener { private int id; public CustomOnClickListener(int id) { this.id = id; } public void onClick(DialogInterface dialog, int which) { //check id and which } } 

Then, when you add onClickListeners to the dialogs, you simply provide the identifier to the listener.

+5
source
 private AlertDialog dialog1; private AlertDialog dialog1; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); dialog1 = new AlertDialog.Builder(this).setTitle("dialog1").create(); dialog1.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", this); dialog2 = new AlertDialog.Builder(this).setTitle("dialog2").create(); dialog2.setButton(AlertDialog.BUTTON_NEGATIVE, "NO", this); } @Override public void onClick(final DialogInterface dialog, final int which) { if (dialog == dialog1) { if (which == AlertDialog.BUTTON_POSITIVE) { // } else if (which == AlertDialog.BUTTON_NEGATIVE) { // } } else if (dialog == dialog2) { if (which == AlertDialog.BUTTON_POSITIVE) { // } else if (which == AlertDialog.BUTTON_NEGATIVE) { // } } } 
+3
source

If your dialogs have differentiable content, you can obviously directly report this in your dialogue:

 if(which==AlertDialog.BUTTON_NEGATIVE)return; AlertDialog theDialog = (AlertDialog)dialog; if(theDialog.findViewById(R.id.phoneinput)!=null) ...;//handle the phone if(theDialog.findViewById(R.id.emailinput)!=null) ...;//handle the email 

Of course, the solution is NOT universal, but in some cases it is very convenient.

0
source

Source: https://habr.com/ru/post/898522/


All Articles