gpt4 book ai didi

android - 为什么按钮会拉伸(stretch)以覆盖分配的所有 layout_weight

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:25:59 25 4
gpt4 key购买 nike

我正在尝试对齐 3 个按钮(左、中、右)。我知道这可能可以通过重力来完成,但我想在这里理解 layout_weight 的概念。我正在使用这段代码:

<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_content 时按钮被拉伸(stretch)以覆盖它分配的所有区域?如何让它像 BOTTOM 图像一样?

enter image description here

谢谢

最佳答案

layout_weight 用于指示屏幕上的额外可用空间应如何在小部件之间分配。在这种情况下,我们有三个具有相同 layout_weight 的按钮,因此按钮将同样增长,直到所有可用空间都消失。

必须尝试其他方法来获得原始大小的按钮和我们想要的对齐方式(左 - 中 - 右)。一个问题是水平 LinearLayout 在尊重 layout_gravity 参数时并不完全协作。我们将能够使用 layout_gravity 参数影响垂直对齐但水平被父 LinearLayout 忽略,叹息另一个死胡同。

一个解决方案是在按钮之间放置一些东西,将它们推到屏幕中的正确位置。 Space View 是在 API 14( Ice Cream Sandwich )中引入的,适合用于此目的。

<?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>

Space View 也可以替换为几个空的 TextView,以使设计适用于运行较早 API 级别的设备。

<TextView
android:id="@+id/textView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="" />

关于android - 为什么按钮会拉伸(stretch)以覆盖分配的所有 layout_weight,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9776845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com