问题:如何将一个按钮居中显示,并占据去父视图宽度的一般?
解决方案:合用weightSum属性和layout_weight属性,具体代码如下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal"
android:weightSum="1" >
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Button" />
</LinearLayout>
效果图如下:
分析:
LinearLayout里面的weightSum属性值,表示其内部所有子视图的weight比例总和,此时设置为1,而Button的layout_weight设置为0.5恰好为其一半,故占据起宽度的二分之一。
扩展
子控件的宽度(根据android:orientation的值会不同,或者是高度)计算结果为:
子控件的width+(weight/weitSum)*(父视图的width-所有子视图的width)