我对安卓系统上的LinearLayout有点问题。我有四个按钮。每个按钮都有固定的大小,但文本的长度可以变化。
我的问题是它们没有与每个元素的顶部对齐。它们看起来与每个按钮内的文本的顶部对齐,这取决于按钮内的行数(见图)。
此外,我希望继续使用LinearLayout,因为我最终将使用基于数据库中的数据添加按钮的代码。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent">
<Button android:text="Line1 Line2" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Button>
<Button android:text="Line1 Line2 Line3" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Button>
<Button android:text="Line1" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Button>
<Button android:text="Line1" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Button>
</LinearLayout>
</LinearLayout>

编辑:答案(无法回答我自己的问题):
好了,我自己找到答案了。您必须向LinearLayout或任何其他可能显示相同行为的类似控件添加android:baselineAligned="false“。
您也可以在UI设计器中使用名为“切换基线对齐”的按钮来修复此问题。
因此,得到的代码是:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:baselineAligned="false" android:layout_width="match_parent" android:layout_height="match_parent">
<Button android:text="Line1 Line2" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Button>
<Button android:text="Line1 Line2 Line3" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Button>
<Button android:text="Line1" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Button>
<Button android:text="Line1" android:textSize="30dp" android:layout_width="160dp" android:layout_height="120dp"></Button>
</LinearLayout>
</LinearLayout>发布于 2011-07-27 12:45:19
对于这种类型的对齐,最好使用RelativeLayout,因为RelativeLayout的概念说它是控件的“引用”
发布于 2011-07-27 12:43:59
我猜你的第二个线性布局会给你带来麻烦,把它去掉就行了
发布于 2011-07-27 12:49:52
您可以使用TableLayout代替第二个LinearLayout.And,在TableLayout中添加一个TableRow,并在行中添加四个按钮
https://stackoverflow.com/questions/6839502
复制相似问题