【问题标题】:How to set width of several views to the largest content width among them? (dynamically)如何将多个视图的宽度设置为其中最大的内容宽度? (动态)
【发布时间】:2013-11-10 11:24:49
【问题描述】:

当我使用静态定义的布局时,我可以通过将wrap_content 设置为LinearLayout layout_widthmatch_parent 作为其子级的layout_width 来做到这一点。
例如,以下 XML 布局定义:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#f88"
    android:orientation="vertical" >

    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#8f8"
        android:text="Smaller"
        />

    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#8f8"
        android:text="I'm a bigger view"
        />
</LinearLayout>

如下所示(请注意,您看不到 LinearLayout 背景颜色,因为它被 TextViews 完全遮住了):

这是期望的结果。但是,如果我在通过 LayoutInflater 动态扩展和添加视图时使用相同的技术,LinearLayout 会被拉伸到屏幕宽度。 (通过使用 LayoutInflater 我的意思是使用 this method 并且我为 root 参数传递了正确的值)
为什么会发生这种情况?那我怎样才能动态地做类似的事情呢?是否可以在 XML 中定义,或者我注定要自己实现该逻辑?

更新:

我在 PopupWindow 中显示布局。当我在 Hierarchy Viewer 中查看 LinearLayout 时,它有 layout_width = match_parent,这很奇怪,因为它在我的 XML 中是 wrap_content

更新 2:

问题是由添加另一个View 宽度为match_parent 引起的。 (用作分隔符)像这样:

<View xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#777" />

似乎它没有“所需宽度”的概念并强制其父级拉伸。

【问题讨论】:

  • 请发布您用于动态添加视图的代码。
  • @DavidWasser 好的。只需要先把它剥离一下......
  • 嗯。在滚动另一个最小示例之后,问题消失了。我会试着弄清楚我原来的方法是怎么回事,如果它不是很愚蠢,作为答案发布(否则 - 删除它)
  • @DavidWasser 似乎代码不是问题。我已经在问答中发布了更多详细信息。

标签: android android-layout


【解决方案1】:

只需将“divider”的视图类从View 更改为TextView 即可解决问题。后者不会尝试获取所有可用空间。但是如果有更优雅的解决方案仍然很有趣(我怀疑为此目的使用 TextView 是矫枉过正而且效率不高)。

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#777" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多