How to set DialogFragment's width and height?

Adil Hussain picture Adil Hussain · Sep 18, 2012 · Viewed 171.6k times · Source

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

Sadly, I find that when my DialogFragment appears, it does not respect the layout_width and layout_height values specified in its xml layout file and thus it shrinks or expands depending on its content. Anyone 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.

Answer

Blix247 picture Blix247 · Oct 16, 2012

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"

You only have to worry about one place (place it in your DialogFragment#onResume). Its not perfect, but at least it works for having a RelativeLayout as the root of your dialog's layout file.