How to set the width of a DialogFragment in percentage?

android-dialogfragment, android-layout

Solution

I don't think it is possible to achieve this without using code.

Anyway I'm using this code inside my custom DialogFragment class. Hope it helps.

public void onResume() {
    super.onResume();

    Window window = getDialog().getWindow();
    Point size = new Point();

    Display display = window.getWindowManager().getDefaultDisplay();
    display.getSize(size);

    int width = size.x;

    window.setLayout((int) (width * 0.75), WindowManager.LayoutParams.WRAP_CONTENT);
    window.setGravity(Gravity.CENTER);
}

Problem

I have a `DialogFragment` with an xml layout and I need it to be, let's say 75% as wide as the screen. When I look for answers I always find the common `weight`-solution, which does not help me, as my fragment overlays the current activity as shown below and does not take the full screen's size. I also don't want to use "ems" as a fix width as I can't know the user's screen size. Is there a way (preferably in xml) to set the root `LinearLayout`'s width to said 75%? I think it would be a possible workaround to define a whole set of `LinearLayout`s and make some of them transparent but this seems to be a rather ugly solution... If it helps, here is the fragment's layout: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_height = "wrap_content" android:layout_width = "match_parent" android:orientation = "vertical" > <EditText android:hint = "@string/inputhint_feedbackName" android:id = "@+id/input_feedbackName" android:imeOptions = "actionNext" android:inputType = "textPersonName" android:layout_height = "wrap_content" android:layout_width = "match_parent" android:lines = "1" android:maxLines = "1" android:singleLine = "true" > <requestFocus /> </EditText> <EditText android:gravity = "top" android:id = "@+id/input_feedbackMessage" android:imeOptions = "actionDone" android:layout_height = "wrap_content" android:layout_marginBottom = "20dp" android:layout_width = "match_parent" android:lines = "10" android:inputType = "textMultiLine" /> <Button android:id = "@+id/button_feedbackSend" android:layout_height = "wrap_content" android:layout_width = "match_parent" android:text = "@string/label_go" android:textSize = "16sp" android:textStyle = "bold" /> </LinearLayout> ```

Original source