我在水平线性布局中有2个按钮和一个TextView。这三个视图都有权重。我一直没有成功将两个按钮垂直居中。
我试过了:
android:layout_gravity="center"
android:gravity="center"
线性布局
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#707070"
>
<Button
android:id="@+id/ratioLBButton"
android:text="LB"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:onClick="ratioLBFunction"
/>
<Button
android:id="@+id/ratioKGButton"
android:text="KG"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:onClick="ratioKGFunction"
/>
<TextView
android:text="Hello World"
android:textSize="18sp"
android:gravity="center"
android:id="@+id/ratioOutput"
android:background="#707070"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="5"
/>
</LinearLayout>
这是包含以上视图的父布局。
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="#989898"
>
这是我的平板电脑的屏幕截图。这与我的Android手机完全相同。
最佳答案
如果使用的是weight
,则需要向父级添加android:weightSum="10"
,这将有助于父级知道应为每个父级分配多少空间。权重之和可以是值。父母的所有孩子也应该这样做。使用android:layout_centerInParent="true"
还会使所有子元素android:layout_width="fill_parent"
。
像这样的东西:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="7">
<Button
android:id="@+id/ratioLBButton"
android:text="LB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:onClick="ratioLBFunction"
/>
<Button
android:id="@+id/ratioKGButton"
android:text="KG"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:onClick="ratioKGFunction"
/>
<TextView
android:text="Hello World"
android:textSize="18sp"
android:gravity="center"
android:id="@+id/ratioOutput"
android:background="#707070"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="5"
/>
每个子项的权重之和必须等于父项的
weightSum
。注意:较小的值将占用更多空间