Search code examples
androidandroid-dialogfragmentandroid-dialog

How to set DialogFragment's width and height?


Let's say I specify the layout of my DialogFragment in an xml layout file named my_dialog_fragment.xml and I specify the layout_width and layout_height values of its root view to a fixed value (e.g. 100dp). I then inflate this layout in my DialogFragment's onCreateView(...) method as follows:

View view = inflater.inflate(R.layout.my_dialog_fragment, container, false);

When my DialogFragment appears, it does not respect the layout_width and layout_height values specified in its xml layout file and instead shrinks or expands depending on its content. Does anybody know whether or how I can get my DialogFragment to respect the layout_width and layout_height values specified in its xml layout file? At the moment I'm having to specify the width and height of the Dialog again in my DialogFragment's onResume() method as follows:

getDialog().getWindow().setLayout(width, height);

The problem with this is that I have to remember to make any future changes to the width and height in two places.


Solution

  • If you convert directly from resources values:

    int width = getResources().getDimensionPixelSize(R.dimen.popup_width);
    int height = getResources().getDimensionPixelSize(R.dimen.popup_height);        
    getDialog().getWindow().setLayout(width, height);
    

    Then specify match_parent in your layout for the dialog:

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    

    Now you only have to worry about one place (i.e. your DialogFragment.onResume method). It's not perfect but at least it works for having a RelativeLayout as the root of your dialog's layout file.