【问题标题】:Make LinearLayout adjust it's height to a TextView with "wrap_content" height使 LinearLayout 将其高度调整为具有“wrap_content”高度的 TextView
【发布时间】:2018-02-27 11:44:33
【问题描述】:

我有一个 LinearLayout 包含一个具有固定高度的 ImageView 和一个 TextView 具有 wrap_content 高度。如果文本不适合一行,我希望 LinearLayout 增长到适合整个 TextView

我的代码:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:orientation="vertical">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="5dp"
        android:scaleType="fitCenter"
        android:src="@drawable/question_mark"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:singleLine="false"
        android:text="Some long text that doesnt fit on one line"/>
</LinearLayout>

上例中的LinearLayout 没有调整大小,所以我只看到"Some long text",然后TextView 的其余部分被隐藏了。

有什么方法可以让LinearLayout根据TextView调整大小?

我知道我可以使用RelativeLayout 和其他类型的布局来实现这一点,但我正在询问使用LinearLayout 的解决方案。

【问题讨论】:

  • 使宽度match_parent成为您的主要布局。
  • 发布您的完整 xml 文件

标签: android android-layout android-linearlayout textview


【解决方案1】:

试试这个:

<LinearLayout android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_margin="5dp"
        android:scaleType="fitCenter"
        android:src="@drawable/ic_launcher_background"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Some long text that doesnt fit on one line"/>

</LinearLayout>

【讨论】:

  • 我将ImageView 上的layout_margin 改为padding,所以我可以在LinearLayoutImageView 上拥有相同的100dp,并且仍然包含ImageViewLinearLayout 内(如果使用边距,则为 110dp)。
  • @BadCash 我没有收到。表示任何问题仍然存在或已完全解决??
  • 完全解决了,谢谢。只是为可能找到此答案的其他人提一下,他们需要调整宽度以考虑边距,或者改用填充。
  • @BadCash 我认为在这种情况下边距和填充是相同的。相反,如果您想要 100 dp 图像,您可以删除边距填充。填充在 imageview 内提供空间,然后 imageview 也将 95 dp。 stackoverflow.com/a/21959146/8089770
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-25
相关资源
最近更新 更多