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.
To create a DialogFragment , first create a class that extends DialogFragment , and override onCreateDialog() , as shown in the following example. Similar to how onCreateView() should create a root View in an ordinary fragment, onCreateDialog() should create a Dialog to display as part of the DialogFragment .
This class was deprecated in API level 28. Use the Support Library DialogFragment for consistent behavior across all devices and access to Lifecycle. A fragment that displays a dialog window, floating on top of its activity's window.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With