为什么按钮会拉伸以覆盖所有已分配的layout_weight

Sna*_*ake 7 android android-layout

我试图让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>
Run Code Online (Sandbox Code Playgroud)

但是,我正在获得下图中的TOP部分.哪个是对的.问题是为什么当我使用wrap_content时按钮被拉伸以覆盖它所分配的所有区域?如何使它像BOTTOM图像一样?

在此输入图像描述

谢谢

Hen*_*ikS 6

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

必须尝试别的东西来获得原始尺寸按钮和我们想要的对齐(左 - 中 - 右).一个问题是,当涉及到layout_gravity参数时,水平LinearLayout不是完全协作的.我们将能够使用影响垂直对齐的layout_gravity参数,但父级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>
Run Code Online (Sandbox Code Playgroud)

Space视图也可以替换为几个空TextView,以使设计适用于运行早期API级别的设备.

<TextView
    android:id="@+id/textView1"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1.0"
    android:text="" />     
Run Code Online (Sandbox Code Playgroud)