android开发笔记之权重(layout_weight)

本文详细解析了在Android开发中LinearLayout中权重layout_weight的工作原理,通过实例展示了不同权重设置下按钮的宽度分配,揭示了权重是如何按比例分配屏幕剩余空间的,并总结了wrap_content、match_parent和0dp情况下权重的特殊表现。
摘要由CSDN通过智能技术生成

我相信大家在布局文件中都用过权重(layout_weight)吧,当然这只有在线性布局(Linearlayout)中才有的,可是很多人也许都只是简单的理解为比。

其实权重就是:
把屏幕剩余空间按比例分配

大家先记住这句话,这里就来深入理解下权重,这里以水平排列为例(即宽度的权重),懂了水平的,竖直排列的(即高度的权重)自然同理。

①第一种情况(宽度为wrap_content):

a.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.example.weight.MainActivity" >
    <Button
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="btn1" />

    <Button
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="btn2" />
</LinearLayout>

这里写图片描述

效果:

这里写图片描述

现在两个按钮的宽度都为wrap_content,所以剩下的屏幕宽度为:

math_parent - 2*wrap_content,权重为1:1

则btn1所占宽度为:本身宽度 + 剩下屏幕的宽度的1/2 = wrap_content
+ 1/2(math_parent - 2*wrap_content)

btn2所占的宽度为:本身宽度 + 剩下屏幕的宽度的1/2 = wrap_content
+ 1/2(math_parent - 2*wrap_content)

从上面看到两式相等,所以两个按钮应该是平分整个屏幕宽度

b.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.example.weight.M
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值