Content Description of Alert Dialog buttons

Viewed 848

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?

2 Answers

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");

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!

Related