控制Dialog的窗口大小(自定义Dialog视图)

来源:互联网 发布:怎么做网络平台 编辑:程序博客网 时间:2024/05/22 19:13

LayoutInflater的坑

LayoutInflater加载布局的时候,会将XML文件中的根View控件大小等属性去除,从而造成在根View中设置视图在大小无效。而Dialog中的父容器默认大小是自动的,其大小于子View大小决定,所以,LayoutInflater加载XML生成的View在Dialog中显示的效果很多是很不理想的。
例子:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:orientation="vertical" >    <EditText        android:id="@+id/text"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="搜索内容" />    <Button        android:id="@+id/btn"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="搜索" /></LinearLayout>

以上这段代码,Dialog的视图大小应该是100DP左右,刚好能完整显示Button。

**

需求:控件Dialog显示大小为300dp

错误的布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="300dp"    android:layout_height="wrap_content"    android:orientation="vertical" >    <EditText        android:id="@+id/text"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="搜索内容" />    <Button        android:id="@+id/btn"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="搜索" /></LinearLayout>

因为LayoutInflater加载XML的时候会将根View的属性去掉,所以在根View中设置的300dp宽度最终会被去掉,造成Dialog的最大大小为刚好能完整显示Button的大小,大约为100dp吧。

正确的布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:orientation="vertical" >    <EditText        android:id="@+id/text"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="搜索内容" />    <Button        android:id="@+id/btn"        android:layout_width="300dp"        android:layout_height="wrap_content"        android:text="搜索" /></LinearLayout>

Button因为不是根View,所以它的大小在LayoutInflater中不会被去除,会完整被加载。根View的大小因为Button子View的大小为300dp而设置自动设置为300dp,所以Dialog的大小也自动设置为300dp了。

自由控件Dialog视图

在XML布局非根View设置想要的大小即可,参照以上例子。

1 0
原创粉丝点击