【问题标题】:Children views having equal height具有相同高度的子视图
【发布时间】:2016-04-26 17:01:00
【问题描述】:

我有一个水平的LinearLayout,里面有两个带有文本的按钮。 LinearLayout 和按钮 layout_height 是 wrap_content。

两个按钮之一的文本占用两行,而另一个按钮占用一行。

所以最后一个按钮的高度比另一个大,这是我不想要的。

我知道如何以编程方式解决这个问题。所以我提出这个问题的原因是想知道我是否可以通过xml来解决这个问题。

一种可能的解决方案是,对于文本为一行的按钮,设置

layout_height="match_parent"

而且效果很好。

但是这里的问题是,一般我不知道哪个按钮会占据最大的高度。

本质上,我想要做的是:拥有一个带有 Views 的 LinearLayout 我想将所有子视图的高度设置为等于视图的高度,该高度在其内容被包装时具有最大高度。

问题是这是否可以通过 xml 实现?

一个示例 XML。另外我忘了补充说我已经有 0dp 的宽度。

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/some_string" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/some_other_string" />

</LinearLayout>

【问题讨论】:

  • 致建议编辑的人:抱歉,由于我进行了后续编辑,它被自动拒绝了。如果你能再发一次,我会接受。
  • 请添加您的布局 xml
  • 虽然问题比较笼统,我还是举个例子吧。

标签: android android-layout android-linearlayout android-xml


【解决方案1】:

我猜你搜索的是android:baselineAligned="false",这样可以避免文本在同一基线上,并且按钮将从屏幕上的同一y位置开始。

这里没有android:baselineAligned="false":

这里有:

但是,如果您还希望两个按钮大小相同,请尝试以下布局示例:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:baselineAligned="false">

    <Button
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="aaaaa"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="bbbbbbb bbbbbbbb bbbbbbbb bbbbbbbbbbbb bbbbbb"/>

</LinearLayout>

看起来像这样:

【讨论】:

  • 所以我们可以在父节点上设置 wrap_content 并在子节点上设置 match_parent 吗?奇怪但很好。谢谢。
  • 是的,从孩子的角度来看,它会匹配父母的大小
【解决方案2】:

用这个东西来设置权重和权重布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="10"
    android:orientation="horizontal" >

    <Button
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="Button 1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="Button 2" />
    </LinearLayout>

    </LinearLayout>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-10
    • 2015-08-24
    • 1970-01-01
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    相关资源
    最近更新 更多