ConstraintLayout wrap the background but constraint horizontally

Viewed 30

I'd like to achieve a simple constraint layout that looks like this

enter image description here

The "Unknown length text", as it's self-explanatory, has an unknown length so it can be either 1 line or multiple lines. The implementation of the text looks like this

<com.google.android.material.textview.MaterialTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginHorizontal="@dimen/twelve_dp"
    android:layout_marginTop="@dimen/four_dp"
    android:background="@drawable/bg_transaction"
    android:paddingHorizontal="@dimen/flow_eight_dp"
    android:paddingVertical="@dimen/flow_two_dp"
    android:textColor="@color/blue_100"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/text_info_2_description"
    tools:text="Unknown length text" />

This has no issue when the text is short, however, when the text becomes long it will not respect the constraint because I have not added the "end-to-end" constraint. So, it will become like this

enter image description here

This can be fixed by making the layout_width="0dp" and adding app:layout_constraintEnd_toEndOf="parent". However, the problem is that the background will take up all the space when the text is short.

enter image description here

<com.google.android.material.textview.MaterialTextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginHorizontal="@dimen/twelve_dp"
    android:layout_marginTop="@dimen/four_dp"
    android:background="@drawable/bg_transaction"
    android:paddingHorizontal="@dimen/eight_dp"
    android:paddingVertical="@dimen/two_dp"
    android:textColor="@color/blue_100"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/text_info_2_description"
    tools:text="short text" />

Is there any way to use the advantage of app:layout_constraintEnd_toEndOf="parent" and make the textview's background only fill the text's width (like in the first screenshot)?

One way of course is to wrap the text view into a frame layout, but I am wondering is there any way to achieve it without an extra layout.

1 Answers

Not sure if you noticed, but the problem is that android:layout_marginHorizontal="@dimen/twelve_dp" is shifting your textview to the right, therefore exceeding the constraint, when you did not explicitly set the constraint. You can either remove that or just set the end-to-end constraint.

You will also need to set the layout width of the textview to wrap_content, so it will conform to the length of the text in the textview.

Related