Android 为什么按钮会拉伸以覆盖所有分配的布局
我试图让3个按钮对齐(左、中、右)。我知道它可能是通过重力来实现的,但我想理解这里的布局重量概念。我正在使用以下代码:Android 为什么按钮会拉伸以覆盖所有分配的布局,android,android-layout,Android,Android Layout,我试图让3个按钮对齐(左、中、右)。我知道它可能是通过重力来实现的,但我想理解这里的布局重量概念。我正在使用以下代码: <LinearLayout id=.. layout_width = "wrap_content" layout_height = "wrap_content" orientation="Horizonta" > <Button id=1 layout_width = "wrap_content" layout_height = "wrap_
<LinearLayout
id=..
layout_width = "wrap_content"
layout_height = "wrap_content"
orientation="Horizonta"
>
<Button
id=1
layout_width = "wrap_content"
layout_height = "wrap_content"
layout_weight = "1"
text= "text" />
<Button
id=2
layout_width = "wrap_content"
layout_height = "wrap_content"
layout_weight = "1"
text= "text" />
<Button
id=3
layout_width = "wrap_content"
layout_height = "wrap_content"
layout_weight = "1"
text= "text" />
</LinearLayout>
然而,我得到了下图的顶部。这是正确的。问题是为什么在我使用wrap_内容时,按钮被拉伸以覆盖分配的所有区域?如何使其像底部图像
谢谢当使用权重时,布局宽度被指定,并且只使用权重算法,然后拉伸元素。您的按钮填满了空间,因为您使用了
layout\u weight=“1”
,告诉按钮占用额外的可用空间,另外,由于所有按钮的layout\u weight
属性为1,因此它们将占用相同的空间并具有相同的大小。使用layout\u weight
无法获得底部布局,请使用layout\u gravity
来定位它们(这里还有另一个问题)
如果您想要下面的图像,请尝试以下操作:
<LinearLayout
id=..
layout_width = "wrap_content"
layout_height = "wrap_content"
orientation="Horizonta"
>
<Button
id=1
layout_width = "wrap_content"
layout_height = "wrap_content"
android:layout_gravity="left"
text= "text" />
<Button
id=2
layout_width = "wrap_content"
layout_height = "wrap_content"
android:layout_gravity="center_horizontal"
text= "text" />
<Button
id=3
layout_width = "wrap_content"
layout_height = "wrap_content"
android:layout_gravity="right"
text= "text" />
</LinearLayout>
布局权重用于指示屏幕上多余的可用空间应如何在小部件之间分配。在这种情况下,我们有三个按钮具有相同的布局重量,因此按钮的增长将相等,直到所有可用空间都消失 必须尝试其他方法来获得原始尺寸的按钮和我们想要的对齐方式(左-中-右)。一个问题是,当涉及布局参数时,水平线性布局不是完全协作的。我们将能够使用布局重力参数,这些参数会影响垂直对齐,但水平方向被父线性布局忽略,这是另一个死胡同 一个解决方案是在按钮之间放置一些东西,将它们推到屏幕上正确的位置。API 14(冰淇淋三明治)中引入了空间视图,适用于此
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<Space
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight = "1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<Space
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight = "1" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
空间视图也可以替换为两个空文本视图,以使设计在运行早期API级别的设备上运行
<TextView
android:id="@+id/textView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="" />
谢谢!我已经做了两个小时了!