TimWalter TimWalter - 22 days ago 10
Android Question

Using an Alertdialog changes the textviews behind

I'm using an AlertDialog to show the result of a game. My problem is that the dialog seems to changes the depiction of my normal activiymain layout while the dialog is open.

That's the layout without the dialog

enter image description here

That's the layout while the dialog is open

enter image description here

As you can see the Textviews that i use as buttons are colored weirdly.
My Dialog is created like this:

AlertDialog.Builder = new AlertDialog.Builder(MainActivity.this);
turnout.setTitle("Dialog");


The mainactivity layout is a relative layout and the textviews are colored in #ffffff (meaning white)

Answer

By default Android dims the background (displays the "grey shadow" behind the dialog) whenever a dialog is displayed. Changing this default behavior may decrease the readability of a dialog and confuse a user.

That being said, you can disable the background by setting the parameter android:backgroundDimEnabled to false in your dialog's style.

You add the theme to your styles.xml:

<style name="NoDimAlertDialog" parent="ThemeOverlay.AppCompat.Dialog.Alert">
    <item name="android:backgroundDimEnabled">false</item>
</style>

Make sure to inherit the default AlertDialog's style.

Additionally you can control the transparency of the dim, using android:backgroundDimAmount. This parameter takes a value from 0 (no dim) to 1 (background completely black). By default Android seems to use 0.6.

<style name="LessDimAlertDialog" parent="ThemeOverlay.AppCompat.Dialog.Alert">
    <item name="android:backgroundDimAmount">0.25</item>
</style>

Next, pass the style name to theAlertDialog.Builder's constructor in your MainActivity.java:

new AlertDialog.Builder(this, R.style.NoDimAlertDialog)
    .setTitle("Some title")
    .setMessage("Some message")
    .show();

You may as well consider using a Fragment to display your AlertDialog. Android comes with handy DialogFragment class for that scenario. A simple DialogFragment in your case may look like that:

class MyDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getContext(), R.style.NoDimDialog)
            .setTitle("Some title")
            .setMessage("Some message")
            .create();
    }
}

Then you add your Fragment in MainActivity.java:

new MyDialogFragment().show(getSupportFragmentManager(), "DialogTag");