【问题标题】:LinearLayout clipping children with TextView width set to wrap_content将 TextView 宽度设置为 wrap_content 的 LinearLayout 裁剪子项
【发布时间】:2017-01-29 22:48:02
【问题描述】:

我有一个包含 TextView 和 ImageView 的 LinearLayout。 TextView 的宽度设置为wrap_content,但问题是当宽度达到父宽度时。文本内容将正确换行至 2 行或更多行,但 TextView 和 ImageView 将在左侧和右侧被剪裁。我能找到的最相似的问题是this one,它是 2013 年的,没有解决方案。

具体来说,我在this view 遇到了这个问题,但我创建了以下更简单的视图来举例说明这个问题:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_top_holder"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/card_top_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="One Two Three Four Five"
        android:textSize="40sp"/>

    <ImageView
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:src="@drawable/ic_volume_up_black_48dp"/>
</LinearLayout>

问题来了: 这是通常的布局:

当布局与另一个视图重叠时,在 LinearLayout 上设置 android:clipChildren="false" 甚至不会阻止剪辑。

这是最终图像,以证明它发生在真实设备上,而不仅仅是布局查看器:

我基本上没有想法。有什么想法吗?这是Android布局系统的问题吗?感谢您的帮助和考虑!

【问题讨论】:

    标签: android android-layout textview android-linearlayout


    【解决方案1】:

    您可以使用android:layout_weight达到预期的效果

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/card_top_holder"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">
    
        <TextView
            android:id="@+id/card_top_text"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="One Two Three Four Five"
            android:textSize="40sp"/>
    
        <ImageView
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:src="@drawable/ic_volume_up_black_48dp"/>
    </LinearLayout>
    

    编辑: 文档中关于 layout_weight 工作原理的一点引用

    LinearLayout 还支持使用 android:layout_weight 属性为单个子级分配权重。这个属性根据它应该在屏幕上占据多少空间来为视图分配一个“重要性”值。较大的权重值允许它扩展以填充父视图中的任何剩余空间。子视图可以指定一个权重值,然后视图组中的任何剩余空间按照其声明权重的比例分配给子视图。默认权重为零。

    例如,如果有三个文本域,其中两个声明权重为 1,而另一个没有权重,则没有权重的第三个文本域不会增长,只会占用其内容所需的区域。在测量所有三个字段后,另外两个将均匀扩展以填充剩余的空间。如果第三个字段的权重为 2(而不是 0),那么它现在被声明为比其他两个更重要,因此它获得总剩余空间的一半,而前两个平分其余空间。

    【讨论】:

    • 是的,这似乎可以解决问题。您对剪裁发生的原因有任何见解,以及为什么会修复它?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    相关资源
    最近更新 更多