androidandroid-layoutandroid-wrap-content

Android Layouts -"wrap_content" is not allowing elements to the right to be displayed if the content width is too wide


This piece I am working on has a design requirement to show on one row some text, followed by an image. The image should always be aligned next to the text like this:

[Some Text] [Img]

[Some longer Text] [Img]

For this, I'm using the "wrap_content" modifier on the width of the text. The issue, however, is when the text is long enough to take up the width of the screen the image is not shown. I am looking for something to help me limit the length of the width (cannot be done dynamically as this needs to load quickly) so that this will always reserve enough space for the image at the end of the line.

So far the only way I've been able to accomplish this is by using a fix width TextView which ends up justifying the image to the same spot on every line, which is not desired. Using anything other than "wrap_content" either requires me to dynamically set the width at run-time or incorrectly creates the TextView wider or narrower than it should be, and the "wrap_content" seems to be what is making it so the image does not display. I have tried RelativeLayout, ConstraintLayout, and LinearLayout to achieve this and all seem to have the same issue.


Solution

  • Use android:drawableRight to display your image instead of using a separate ImageView.

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:drawableRight="@drawable/android"
        android:text="short text"/>
    

    enter image description here

    enter image description here

    You can use android:gravity to control the vertical position of the text/image and android:drawablePadding to control the space between the image and the text.