I have a TextView whose width should not exceed the ImageView above it. Both image and text are downloaded from server and I don't know their dimensions (can't make assumptions either). I went through the logic to wrap the text content using this SO post.
Here is my layout XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parentLL"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout android:orientation="vertical"
android:id="@+id/LL1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:width="0dp"
android:text="This is a string whose width may or may not be more than the image downloaded" />
</LinearLayout>
<TextView android:background="@android:color/holo_red_dark"
android:id="@+id/text2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Second Text"/>
</LinearLayout>
With this code, the TextView at the end (text2) does not even show up. There are 2 solutions to this issue :
- Apply android:maxLines="5" to the text1. Problem with this approach is that Text1 view would always be 5 lines high (I understand 'lines' is not a unit of height, but that's what I see visually). So if the text content is just one word, there would be a big white space below. And then text2 shows up.
- Change topmost linear layout (parentLL) to RelativeLayout. text2 can then be used with alignBelow=LL1. This works as expected. But I cannot migrate the topmost view to RelativeLayout, because this view is from a library not in my control. I can only modify LL1 and it's children. Due to my code, other views below (like text2) are suffering (by not showing up).
- There is a third approach for setting the textview as a compound drawable on ImageView. I guess that might work (haven't tested), but my requirement is to show the TextView if image download has failed (which can be detected only after a while). So I need to have a TextView. Also, my LinearLayout LL1 can have other children too.
I would request for some help understanding :
- Why is my code not showing up the content below the textview 'text1'? With width=0 on textview it seems to set the height of the parent to be match_parent.
- How is RelativeLayout able to handle this smoothly ? Can I replicate any of that behavior in TextView's onMeasure ? Assume I have callbacks to detect image has been downloaded, and I can get image width also.