线性布局 - 垂直方向未对齐

18

我在Android上使用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>

http://i.imgur.com/0Kj8h.png

编辑:答案(无法回答自己的问题):

好的,我刚刚自己找到了答案。 您需要在LinearLayout或任何其他可能显示相同行为的控件中添加android:baselineAligned="false"。

您也可以使用名为“Toggle Baseline Alignment”的按钮在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>

1
谢谢你提供关于android:baselineAligned="false"的提示,它也解决了我的问题 :-) - James Goodwin
3个回答

1

对于这种类型的对齐,最好使用RelativeLayout,因为RelativeLayout的概念是“引用”控件。


0

嗯,我猜你遇到了麻烦的原因是第二个线性布局,只需将其删除即可。


我需要保留它,因为它周围会有其他的东西,比如一个标题,但是你说得很好。 - darkzangel

0
你可以使用TableLayout代替你的第二个LinearLayout。在TableLayout内添加一个TableRow,在行内添加四个按钮。

TableLayout如果将所有项目放在同一个单元格中,则会执行相同的操作。 此外,正如我所说,我想保持LinearLayout,因为最终我将通过代码添加未知数量的按钮。 我不知道这些按钮中会显示什么,因此需要保持一种简单的方式来将它们显示为流。 此外,当屏幕旋转时,它将自动调整。 - darkzangel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接