如何设置DialogFragment的宽度百分比?

时间:2014-11-17 13:44:51

标签: android-layout android-dialogfragment

我有一个带有xml布局的DialogFragment,我需要它,让我们说75%的宽度与屏幕一样宽。当我寻找答案时,我总能找到常见的weight - 解决方案,这对我没有帮助,因为我的片段覆盖了当前活动,如下所示,并没有采用全屏的大小。我也不想使用" ems"作为固定宽度,因为我无法知道用户的屏幕尺寸。

enter image description here

有没有办法(最好用xml)将根LinearLayout的宽度设置为75%?我认为这可能是一种可行的解决方法,可以定义一整套LinearLayout并使其中一些透明,但这似乎是一个相当难看的解决方案......

如果有帮助,这里是片段的布局:

<?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>

2 个答案:

答案 0 :(得分:39)

我认为不使用代码就可以实现这一点。

无论如何,我在我的自定义DialogFragment类中使用此代码。希望它有所帮助。

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);
}

答案 1 :(得分:2)

您可以通过在onCreate方法上为对话片段设置样式来实现此目的:

setStyle(DialogFragment.STYLE_NORMAL,R.style.yourStyle);

并在你的styles.xml中

   <style name="yourStyle" parent="android:Theme.Dialog">
        <item name="android:windowBackground">@drawable/some_background</item>
        <item name="android:windowAnimationStyle">@null</item>
        <item name="android:backgroundDimEnabled">false</item>
        <item name="android:windowMinWidthMajor">75%</item>
        <item name="android:windowMinWidthMinor">75%</item>
        <item name="android:windowNoTitle">true</item>
    </style>
相关问题