2

I have a LinearLayout containing an ImageView with fixed height, and a TextView with wrap_content height. I want the LinearLayout to grow to fit the entire TextView if the text doesn't fit on one line.

My code:

<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>

The LinearLayout in the example above doesn't resize, so I only see "Some long text" and then the rest of the TextView is hidden.

Any way to get the LinearLayout to resize according to the TextView?

I know I can use RelativeLayout and other types of layouts to achieve this, but I'm asking about a solution using LinearLayout.

Magnus
  • 17,157
  • 19
  • 104
  • 189

1 Answers1

1

Try this :

enter image description here

<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>
Vidhi Dave
  • 5,614
  • 2
  • 33
  • 55
  • 1
    I changed the `layout_margin` on the `ImageView` to `padding` instead, so I can have the same `100dp` on the `LinearLayout` and `ImageView` and still contain the `ImageView` inside the `LinearLayout` (it will be 110dp if using margin). – Magnus Feb 27 '18 at 12:02
  • @BadCash I am not getting. means any issue still remains or it is fully solved?? – Vidhi Dave Feb 27 '18 at 12:05
  • 1
    It's fully solved, thanks. Just mentioning for others who might find this answer that they need to adjust the width to account for margins, or use padding instead. – Magnus Feb 27 '18 at 13:52
  • @BadCash I think margin and padding are same in this case. instead if you want 100 dp image you can remove margin padding. padding provides space inside imageview then imageview will also 95 dp. https://stackoverflow.com/a/21959146/8089770 – Vidhi Dave Feb 28 '18 at 04:09