线性布局:在Android中将两个按钮并排放置

15

我有一个布局文件 layout.xml,其中有三个按钮,它们按照下面的方式依次排列...

                <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:padding="10dip" >

                    <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <Button
                        android:id="@+id/btn_1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="Car" />

                    <Button
                        android:id="@+id/btn_2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="Vehicle" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical" >

                    <Button
                        android:id="@+id/btn_3"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Bike" />
                </LinearLayout>
            </LinearLayout>

我希望把前两个按钮(btn_1和btn_2)放在一起。请问有没有人能给我一些提示该如何实现?

非常感谢!


这是同样的情况:https://dev59.com/w2035IYBdhLWcg3wNtRw#21411490 - iarroyo
3个回答

19

只需要将您的布局中的android:orientation="vertical"更改为android:orientation="horizontal",所有事情都会正常工作。


9
最好的方法是制作布局,然后按照以下代码放置按钮。
<TableRow 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

 <Button 
    android:id="@+id/Button9"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="left"
    android:text="@string/Home1"/>  

 <Button 
    android:id="@+id/Button11"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right"     
    android:text="@string/NextL"/>

在这个形状中,您有两个按钮在同一行中,非常容易:D

似乎你忘记了一个闭合标签?此外,根据文档,“TableRow应始终用作TableLayout的子级”。 - dst
是的,我忘记了那些内容,但并不是必须的。它们可以在大多数布局中使用。我在一个LinearLayout中使用了它们,效果很好。 - user3287335
这就是为什么文档中只提到“应该”而不是“必须”的原因。但由于文档建议不要这样做,我也不建议在新的Android版本中出现问题时使用它。 - dst

3

将线性布局方向从垂直改为水平。然后给你的两个按钮分别设置权重为1或2,根据你的意愿。这样,按钮将被平均排列。


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