nathanielwolf
nathanielwolf

Reputation: 567

DialogFragment size (width) ignored

I'm using a DialogFragment and found the width always becomes always fullscreen when I make an inner LinearLayout's layout_width=match_parent, no matter how many contraints I try to force on it by fixing the layout_width and minWidth of the parent view, or setting the Layout dimens in CreateView()

dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="@dimen/dialog_width"
android:layout_height="@dimen/dialog_height"
android:minWidth="@dimen/dialog_width"
android:minHeight="@dimen/dialog_height"
android:orientation="vertical" 
android:paddingTop="5dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    ...
    </LinearLayout>
</LinearLayout>

Dialog.java

public class MyDialog extends DialogFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ...
        Resources r = getActivity().getResources();
        getDialog().getWindow().setLayout( (int)r.getDimension(R.dimen.dialog_width), (int)r.getDimension(R.dimen.dialog_height));
        return view;
    }
}

The only way I can make this work is by setting the inner LinearLayout layout_width="@dimen/dialog_width

hacked dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
... >

<LinearLayout
    android:layout_width="@dimen/dialog_width"
    android:layout_height="wrap_content">
    ...
    </LinearLayout>
...
</LinearLayout>

Which works okay, but has some consequences for other parts of the dialog. Is this a bug in Android?

Upvotes: 10

Views: 4164

Answers (2)

Kirit  Vaghela
Kirit Vaghela

Reputation: 12664

Replace you code with this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="@dimen/dialog_width"
android:layout_height="@dimen/dialog_height"
android:minWidth="@dimen/dialog_width"
android:minHeight="@dimen/dialog_height"
android:orientation="vertical" 
android:paddingTop="5dp">
    ...
</LinearLayout> 

Use only one LinearLayout and put all the things in it

Upvotes: -2

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

I haven't seen any documentation on this, but I read somewhere (probably on SO) that the root layout's layout_width and layout_height parameters are over-ridden with 'wrap_content' when the dialog is created.

I'm not sure whether that's actually true or not, but the layout behavior that I've seen suggests that it's true. Anyway, I've gotten my dialogs to layout properly by assuming that this is the case.

You might want to try wrap_content on your inner layouts as well, wherever possible. Hardcoded widths tend not to work well across multiple devices.

Upvotes: 3

Related Questions