日积月累:weightSum和layout_weight属性合用

讲解一:weightSum和layout_weight属性合用 

  • android:weightSum属性:定义weight总和的最大值。如果为指定该值,所有子视图的layout_weight属性的累加值作为总和的最大值。例如,通过指定子视图的layout_weight属性为0.5,并设置LinearLayout的weight属性为1.0,实现子视图占据可用宽度的50%; 

  • layout_weight属性:子视图的控件比例。就像我们在盒子放置其他物体,盒子可用空间的比例就是weightSum,盒子每个控件的比例就是layout_weight。 

 

下面我们通过一个具体的需求,结合两个属性实现。需求如下:居中显示按钮,并占据父控件的50%宽度。编写布局文件main_activity.xml文件如下: 

<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:gravity="center_horizontal" 
    android:weightSum="1.0" 
    tools:context=".MainActivity" > 
    <Button 
        android:layout_width="0dp" 
        android:layout_height="wrap_content" 
        android:layout_weight="0.5" 
        android:text="@string/hello_world" /> 
</LinearLayout> 

效果如下图 



























分析如下 

  1. android:gravity="center_horizontal":实现按钮居中显示 

  2.  android:weightSum="1.0"、android:layout_width="0dp"和android:layout_weight="0.5":按钮的宽度=按钮本身的宽度+按钮的weight*父控件的宽度/父控件的weightSum;即:按钮的宽度=0dp+0.5*父控件的宽度/1.0=0.5父控件的宽度; 

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值