假设我在一个名为my_dialog_fragment.xml的xml布局文件中指定了我的DialogFragment的布局,并且我将其根视图的layout_width和layout_height值指定为固定值(例如100dp)。然后我在我的DialogFragment的onCreateView(…)方法中膨胀这个布局,如下所示:

View view = inflater.inflate(R.layout.my_dialog_fragment, container, false);

可悲的是,我发现当我的DialogFragment出现时,它不尊重layout_width和layout_height值在其xml布局文件中指定,而是根据其内容收缩或展开。有人知道我是否或如何得到我的DialogFragment尊重layout_width和layout_height值指定在其xml布局文件?目前,我必须在我的DialogFragment的onResume()方法中再次指定对话框的宽度和高度,如下所示:

getDialog().getWindow().setLayout(width, height);

这样做的问题是,我必须记住将来在两个地方对宽度和高度进行任何更改。


当前回答

我没有看到一个令人信服的理由重写onResume或onStart来设置DialogFragment的Dialog中的窗口宽度和高度——这些特定的生命周期方法可以被反复调用,不必要地执行调整代码多次,由于多窗口切换,后台然后前景应用等事情。这种重复的后果是相当微不足道的,但为什么要满足于此呢?

在重写的onActivityCreated()方法中设置宽度/高度将是一个改进,因为这个方法实际上只会在每个DialogFragment实例中调用一次。例如:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Window window = getDialog().getWindow();
    assert window != null;

    WindowManager.LayoutParams layoutParams = window.getAttributes();
    layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
    window.setAttributes(layoutParams);
}

上面我只是将宽度设置为match_parent,而不考虑设备方向。如果你想要你的横向对话框不那么宽,你可以检查getResources(). getconfiguration()。orientation == Configuration。事先ORIENTATION_PORTRAIT。

其他回答

我修复了它设置根元素布局参数。

int width = activity.getResources().getDisplayMetrics().widthPixels;
int height = activity.getResources().getDisplayMetrics().heightPixels;
content.setLayoutParams(new LinearLayout.LayoutParams(width, height));

使用RelativeLayout作为DialogFragment的父元素

你可以下面的代码设置布局的宽度和高度从java。

final AlertDialog alertDialog  = alertDialogBuilder.create();
final WindowManager.LayoutParams WMLP = alertDialog.getWindow().getAttributes();

WMLP.gravity = Gravity.TOP;
WMLP.y = mActionBarHeight;
WMLP.x = getResources().getDimensionPixelSize(R.dimen.unknown_image_width);

alertDialog.getWindow().setAttributes(WMLP);
alertDialog.show();

这将会非常有效。

@Override
public void onResume() {
    super.onResume();
    Window window = getDialog().getWindow();
    if(window == null) return;
    WindowManager.LayoutParams params = window.getAttributes();
    params.width = 400;
    params.height = 400;
    window.setAttributes(params);
}

下面是在xml中设置DialogFragment宽度/高度的方法。只需要用一个透明背景的框架布局(任何布局都可以)来包装你的viewherarchy。

透明背景似乎是一个特殊的标志,因为当你这样做时,它会自动将framayout的子元素居中。您仍然会在您的片段后面看到全屏变暗,这表明您的片段是活动元素。

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/transparent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:background="@color/background_material_light">

      .....