Michel Jung Michel Jung - 1 year ago 185
Android Question

AlertDialog style when using setView()

The Default AlertDialog looks nice, and using setMessage() one can set its text - easy.

But when using setView(), the dialog replaces the content by the given view, which is fine.

However, I'd like to keep the default paddings/background/style. I searched for a proper style and I had a look at alert_dialog.xml, but didn't find anything helpful.
enter image description here

How can I apply the default style, without mimicking it?

Answer Source

There is an AlertDialog style, that you can set when you create your Builder.


    AlertDialog.Builder builder;
    if (title != null) {
        builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogStyle);
    else {
        builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogStyleNoTitle);

In your styles.xml file:

<style name="AlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>
    <item name="android:textColorPrimary">@color/black</item>

<style name="AlertDialogStyleNoTitle" parent="AlertDialogStyle">
    <item name="android:windowNoTitle">true</item>

My styles are just an example of some things you can do - you can just have one dialog style if you want. As long as you inherit from one of the Dialog.Alert styles, you should be good to go.

You will still have to set the padding up yourself. I looked at the material design guidelines, and the margins are 24dp.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download