Search code examples
androidandroid-layoutandroid-constraintlayout

Max width in Constraint Layout


I am working on a chat app. I want the message (text view) to always start 20px from the left of the screen. When the message is short, the text view's width is wrap content. But when the message is long, the text view will reach 50px to the right of the screen. How to achieve it.

short text

short text

enter image description here

long text


Solution

  • Use app:layout_constrainedWidth="true" with app:layout_constraintHorizontal_bias="0"

    The following works for me:

    <TextView
            android:text="sampleskdjfalksfasdkfjakllksdajfkljaskfdlasdjfklajdfklajkf"
            app:layout_constraintTop_toTopOf="parent"
            android:layout_marginTop="50dp"
            android:layout_marginStart="20dp"
            app:layout_constrainedWidth="true"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0"
            android:layout_marginEnd="50dp"
            app:layout_constraintStart_toStartOf="parent"
            android:background="#666"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>