Search code examples
androiddialogwidth

DialogFragment takes whole screen width


in my android app I'm using DialogFragment extending class to show custom dialogs, but I have a problem all created dialogs take whole screen width (example in photo), I would prefer it come with margin, how to do it?

my dialog


Solution

  • one way is to use style for it. You could create your custom style, like

    <style name="AlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
        <!-- Used for the buttons -->
        <item name="colorAccent">@color/black</item>
        <item name="android:textColorPrimary">@color/black</item>
        <item name="android:windowMinWidthMajor">80%</item>
        <item name="android:windowMinWidthMinor">80%</item>
        <!-- Used for the background -->
        <item name="android:windowBackground">@color/white</item>
    </style> 
    

    and onCreate of your DialogFragment subclass you can provide it as parameter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.AlertDialogStyle)
    

    you can find a description of the key items in the style here