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

 

posted @ 2014-10-27 15:41  perfect亮  阅读(585)  评论(0编辑  收藏  举报