HackOne

使用 weight 属性实现视图的居中显示

一.在开发中有时候会遇到将一个控件在父控件居中显示。但是如果你直接用margin_*来进行限制的话就可能造成对于不同的型号的手机又不同显示的格式。

 

所以就可以用到android:weightSum和android:layoutweight来解决这个问题。

 

官方API对android:weightSum的解释是:

 

    定义weight总和的最大值。如果未指定该值,以所有子视图的layout_weight属性的累加值作为总和的最大值。

 

一个典型的案例是:通过制定子视图的layout_weight属性为0.5,并设置LinearLayout的weightSum属性为1.0,实现子视图占据可用宽度的50%
.代码:
 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="vertical"
 6     tools:context=".MainActivity" >
 7 
 8     <LinearLayout
 9         android:layout_width="200dp"
10         android:layout_height="200dp"
11         android:gravity="center"
12         android:weightSum="1.0" >
13 
14         <Button
15             android:id="@+id/btn"
16             android:layout_width="0dp"
17             android:layout_height="wrap_content"
18             android:layout_weight="0.5"
19             android:text="居中显示" />
20     </LinearLayout>
21 
22 </LinearLayout>

显示的效果是:

PS:可能有人会对上面的android:layout_width="0"有疑问,用android:weight有个计算公式的:

  Button‘s width + Button’s weight*200/sum(weight)

  因为制定了Button的宽度为0dp,Button的weight为0.5,sumWeigh为1所以结果如下:

  0 + 0.5 * 200/1=100

 

转载于:https://www.cnblogs.com/liangstudyhome/p/4054349.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值