如何设置 DialogFragment 的宽度和高度? [英] How to set DialogFragment's width and height?

查看:150
本文介绍了如何设置 DialogFragment 的宽度和高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在名为 my_dialog_fragment.xml 的 xml 布局文件中指定了我的 DialogFragment 的布局,并指定了 layout_widthlayout_height 将其根视图的值设置为固定值(例如 100dp).然后我在我的 DialogFragmentonCreateView(...) 方法中扩展这个布局,如下所示:

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

遗憾的是,我发现当我的 DialogFragment 出现时,它不遵守其 xml 布局文件中指定的 layout_widthlayout_height 值,并且因此它会根据其内容缩小或扩大.任何人都知道我是否或如何让我的 DialogFragment 遵守其 xml 布局文件中指定的 layout_widthlayout_height 值?目前,我必须在我的 DialogFragmentonResume() 方法中再次指定 Dialog 的宽度和高度,如下所示:

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.

推荐答案

如果直接从资源值转换:

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

然后在对话框的布局中指定 match_parent:

Then specify match_parent in your layout for the dialog:

android:layout_width="match_parent"
android:layout_height="match_parent"

你只需要担心一个地方(把它放在你的 DialogFragment#onResume 中).它并不完美,但至少它适用于将 RelativeLayout 作为对话框布局文件的根目录.

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.

这篇关于如何设置 DialogFragment 的宽度和高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆