Wrap_content view inside a ConstraintLayout stretches outside the screen

Marcin Jedynak picture Marcin Jedynak · Nov 28, 2016 · Viewed 60.3k times · Source

I am trying to implement a simple chat bubble using a ConstraintLayout. This is what I am trying to achieve:

enter image description here enter image description here

However, wrap_content seem not to work properly with constraints. It respects the margins, but doesn't calculate the available space properly. Here is my layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout   xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/chat_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintHorizontal_bias="0"
        tools:background="@drawable/chat_message_bubble"
        tools:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sodales accumsan tortor at bibendum."
        android:layout_marginStart="64dp"
        android:layout_marginLeft="64dp"
        android:layout_marginEnd="32dp"
        android:layout_marginRight="32dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp" />
</android.support.constraint.ConstraintLayout>

This renders as follows:

enter image description here

I am using com.android.support.constraint:constraint-layout:1.0.0-beta4.

Am I doing something wrong? Is it a bug or just an unintuitive behavior? Can I achieve the proper behavior using a ConstraintLayout (I know I can use other layouts, I am asking about ConstrainLayout specifically).

Answer

Silvia H picture Silvia H · Oct 19, 2017

Updated (ConstraintLayout 1.1.+)

Use app:layout_constrainedWidth="true" with android:layout_width="wrap_content"

Previously (deprecated):

app:layout_constraintWidth_default="wrap" with android:layout_width="0dp"