Android 父控件wrap_content随笔

本文探讨了Android中id为layout_parent的父控件wrap_content如何根据子控件高度进行计算。当子控件设置固定高度时,父控件高度将根据最大固定高度确定;若所有子控件未设定固定高度,则父控件高度由子控件实际高度决定。总结了wrap_content在不同情况下的计算优先级。

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

<pre name="code" class="html"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_parent"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/holo_green_light"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/img1"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:src="@drawable/ic_launcher" />

    <ImageView
        android:id="@+id/img2"
        android:layout_width="164dp"
        android:layout_height="164dp"
        android:background="@android:color/holo_orange_light"
        android:src="@drawable/ic_launcher" />

    <LinearLayout
        android:id="@+id/layout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/holo_purple"
        android:orientation="vertical" >
    </LinearLayout>

</LinearLayout>


 

如上  先上结论 id为 layout_parent 的父控件里的wrap_content 是根据子控件的height 来计算的,计算的优先级是如果子控件中设置了固定高度,则计算 "固定高度",如 64dp 。计算固定高度时会根据最大的高度来计算父控件的高度。如果子控件中没有固定高度,则根据子控件的高度来计算父控件的高度


如上边的代码,父控件中的height 为 wrap_content,即根据内容设置高度。而它的子控件中img1,img2都为 固定数值 ,即有明确数字,则根据较大的数值,即img2的164dp得到父控件(layout_parent)的高度为164dp。  子控件layout1的高度为match_parent 即填充父类,则layout1的高度也为164dp

计算父控件大小的优先级:(父控件设置为wrap_content的前提下)

子控件设置固定大小的情况下:则根据 “设置最大固定大小的子控件的大小” 来计算父控件的大小,不计算match_parent,fill_parent;

子控件未设置固定大小的情况下:则根据 子控件的大小计算父控件的大小,如子控件为match_parnet,则父控件大大小即为填充屏幕


随笔

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值