android多设备界面适配的利器:属性weight的妙用

本文详细介绍了在界面布局中如何使用布局权重属性来实现控件按比例显示及一个控件独占而其他控件根据内容自动调整的功能。通过具体的XML示例代码,展示了EditText与Button控件如何分配剩余空间。

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

1、按比例显示控件元素

    <EditText
        android:id="@+id/edit_message"
        android:layout_weight="2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" >
        <requestFocus />
    </EditText>
    
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/button_send" />


属性weight的作用(不翻了,将就看吧):

if you give one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view fills 2/3 of the remaining space and the second view fills the rest. If you add a third view and give it a weight of 1, then the first view (with weight of 2) now gets 1/2 the remaining space, while the remaining two each get 1/4.

EditText 占 2/3  ,  Button 占 1/3. 

 

注意:只有当这两个控件的layout_width、layout_height都设置为"wrap_content"时,这个规则才能够成立。

2、一个控件独占,其它控件根据自身内容自动调整。

将需要独占的控件,其weight设置为1,同时宽度设置为0dp。根据自身内容调整的控件,不要设置weight。

效果:

 

转载于:https://www.cnblogs.com/ygm900/p/3521328.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值