Adil Hussain Adil Hussain - 3 months ago 27
Android Question

How to set DialogFragment's width and height?

I specify the layout of my DialogFragment in an xml layout file (let's call it

layout_mydialogfragment.xml
), and its
layout_width
and
layout_height
attributes particularly (to be
100dp
each let's say). I then inflate this layout in my DialogFragment's
onCreateView(...)
method as follows:

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


Unfortunately, I find that when my dialog (DialogFragment) appears, it does not respect the
layout_width
and
layout_height
specified in its xml layout file (and my dialog shrinks or expands variably depending on content). Anyone know whether or how I can get my dialog to respect the
layout_width
and
layout_height
specified in its xml layout file? At the moment I'm having to specify the width and height of my dialog again in my DialogFragment's
onResume()
method as follows...

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


... And thus, undesirably, have to remember to make any future changes to the dialog's width and height in two places.

Answer

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.

Comments