如果我想将按钮居中显示,并且占据其父视图宽度的一半
效果演示:
使用windthSum属性和layout_width属性
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:weightSum="1">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Hello World!" />
</LinearLayout>
其中
android:weightSum=”1” 表示内部所有子视图的weight总和是1,
android:layout_weight=”0.5” 表示Button将占据50%的可用空间
计算 Button 宽度的公式(以屏幕宽度200dp计算)
Button width + Button weight * 200 / sum(weight)