Yes, there is a better way to expose AlertDialogs for your automation code, but you have to do this in production code. It will be worth it because it will make your life a lot easier. Let me explain.
You can assign your AlertDialogs to a WeakHashMap object and get them very easily. Here's how -
WeakHashMap< Integer, Dialog > managedDialogs = new WeakHashMap< Integer, Dialog >();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(YourActivity.this);
switch(id)
{
case DIALOG:
alertDialogBuilder.setTitle("some title")
.setMessage("some message")
.setPositiveButton("button text", Onclick activity)
.setNeutralButton("button text", Onclick activity)
.setNegativeButton("button text", Onclick activity)
.setCancelable(true);
AlertDialog dialog = alertDialogBuilder.create();
managedDialogs.put(DIALOG, dialog);
return dialog;
}
Now in the test environment, when you are waiting for the dialog to appear, just do -
AlertDialog dialog = (AlertDialog) activity.managedDialogs.get(YourActivity.DIALOG);
source
share