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

本文探讨了在Android中使用LayoutInflater加载Dialog布局时遇到的问题,由于LayoutInflater会忽略XML根View的大小属性,导致Dialog大小无法按预期设置。通过示例说明,错误地在根View设置大小会失效,而正确做法是在非根View上设置大小,以达到控制Dialog显示为300dp的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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设置想要的大小即可,参照以上例子。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值