Tuesday, 27 November 2012

Android: DialogFragment - dialog sizing

If you've played about creating dialogs using the DialogFragment class, you've probably noticed that the layout_width and layout_height parameters you assign in the xml layout file for your dialog are ignored (disrespected!) and the DialogFragment assigns height and width to the dialog however it so wishes!

Because of this problem and because it is highly recommended to create dialogs with the DialogFragment class, what I do now is to specify the layout_width and layout_height parameters in the xml layout file to have value match_parent. And then, more importantly, what I do is to specify the dialog's size (height and width) in my DialogFragment.onStart() method as follows:

public void onStart() {

  // safety check
  if (getDialog() == null) {

  int dialogWidth = ... // specify a value here
  int dialogHeight = ... // specify a value here

  getDialog().getWindow().setLayout(dialogWidth, dialogHeight);

  // ... other stuff you want to do in your onStart() method


Anonymous said...

Thank you !

Anonymous said...

I was searching an answer for this problem for some time and found it here. Thank you very much for this post.

Anonymous said...

Searching for this answer way long .Thankyou!!!

Anonymous said...

Simple and well explained solution! Thanks a lot!;)

Anonymous said...

it works but it seems to show dialog on top of screen not center

Kavitha Nagarajan said...

your solution is not working for me,if i use the code like below

` if (getDialog() == null) {

int dialogWidth = 1000;
int dialogHeight = LayoutParams.WRAP_CONTENT;
getDialog().getWindow().setLayout(dialogWidth, dialogHeight);

How to use both?

Thanks in advance

adil said...

Kavitha, you want: if (getDialog() != null) {...your code here...}

Anonymous said...

Very much thanks for your post. That helped me a lot.

munisekhar rangineni said...

i am all ways getting dialog is null value

Saeid said...

Thanks man! That was very helpful!

Saeid said...
This comment has been removed by the author.
avincoder said...

Unfortunately this alone may not work.
If you want to force dialog size, then also make sure that your contentview (layout for dialog) is in RelativeLayout(with match parent). Linearlayout and Framelayout(even with match parent) will not work sometimes.

Surya Pandian said...

Hi... what if I want to make the height of my dialog fragment 60% of the entire screen.. what should I try????

adil said...

Surya, can you not get the height of the screen, work out 60% of it and then set that as the height of the dialog?

┼×ahin Atam said...

Hi Adil,

I have another kind of question about animations.I asked on stackoverflow, but no answer, can you help me ?


Fernando Ferreira said...

Thank you for your explanation. It helped me so much.

hai said...

Thanks so much!