Home » Android » android – How to select which button to click on Robotium for an alert dialog?

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

Posted by: admin May 14, 2020 Leave a comment

Questions:

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.

How to&Answers:

Just use solo.clickOnButton(“Cancel”);

Answer:

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.