2

I'm displaying an AlertDialog as follows:

private void showAlertDialog(String message){
    new AlertDialog.Builder(MainActivity.this)
        .setMessage(message)
        .setPositiveButton(android.R.string.ok, null)
        .show();
}

I would like to run automation tests which relay on android:contentDescription to read values.

Is it possible to add/get this parameter from Positive and Negative Button of built-in Alert Dialog?

guipivoto
  • 18,327
  • 9
  • 60
  • 75
Evgeniy Mishustin
  • 3,343
  • 3
  • 42
  • 81

2 Answers2

3

I already answered in comment, Just to Close the question with an accepted answer...

You can get Dialog's action Button Using #alertDialog.getButton() ... In this particular case You can use :-

alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setContentDescription("positive");
alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setContentDescription("negative");
ADM
  • 20,406
  • 11
  • 52
  • 83
  • 3
    Note: should use this after alertDialog.show() or else you will get an NPE – Evgeniy Mishustin Jun 19 '19 at 07:33
  • Yeah i forget to add that .. Here is [Full reference](https://stackoverflow.com/questions/4604025/alertdialog-getbutton-method-gives-null-pointer-exception-android). – ADM Jun 19 '19 at 07:36
1

Checking file alert_dialog.xml at ANDROID_HOME/platforms/android-28/data/res/layout, I can see the buttons from a REGULAR/STANDARD AlertDialog is defined as follow:

<Button android:id="@+id/button1"
    android:layout_width="0dip"
    android:layout_gravity="start"
    android:layout_weight="1"
    ... />
<Button android:id="@+id/button3"
    android:layout_width="0dip"
    android:layout_gravity="center_horizontal"
    android:layout_weight="1"
    ... />
<Button android:id="@+id/button2"
    android:layout_width="0dip"
    android:layout_gravity="end"
    android:layout_weight="1"
    ... />

Then, you can search those views and get their content as follows:

AlertDialog alert = builder.create();
alert.findViewById(android.R.id.button1);

EDIT

As mentioned by @ADM in the comments, you can easily run the code below:

You can set it by alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setContentDescription("positive");

Easier and simple.. And you don't need to rely on the View ID.. very good (and best) solution!

guipivoto
  • 18,327
  • 9
  • 60
  • 75