How to select which button to click on Robotium for an alert dialog?

Kavin Arasu picture Kavin Arasu · Apr 28, 2012 · Viewed 8.2k times · Source

I am new to Robotium. I have created an alert dialog box using dialog builder and called it using the show command. I was able to trigger the 'ok' button by default using Robotium and I am not able to do the same for the 'cancel' button. As the dialog box is not associated with an id, I am not sure how to get the id of the buttons. Here is my code for the dialog box

alertDialogBuilder
.setMessage("Please enter only numbers without any spaces")
.setCancelable(true)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog, int id) {
 dialog.cancel();
 }
 })
 .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog, int id) {
 dialog.cancel();
 }
 });

The code I used to trigger the 'ok' button in the Test Class is

 solo.getCurrentActivity().runOnUiThread(new Runnable() {
 public void run() {
 solo.getCurrentActivity().getCurrentFocus().requestFocus();
 }
 });
 this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);

How to do the same for the 'cancel' button? Thanks in advance.

Answer

Avi Cherry picture Avi Cherry · Jun 2, 2012

Actually, I suggest you do solo.clickOnView(solo.getView(buttonId)) where the 'Positive' button is android.R.id.button1, the 'Negative' button is android.R.id.button2 and 'Neutral' is android.R.id.button3.