Search code examples
javaandroidbuttonmarginline-breaks

Issues with multiline button texts ignoring button margins


Basically I have a button with a pretty long string which causes a line-break. The button has margins left and right which are however ignored with such multi line button texts as the button takes up the full width of the parent.

An obvious solution is to set the layout width to 0dp which however forces a static width meaning for a shorter buttontext the button is no longer wrapped.

Is there a good solution how to keep wrap_content for the width but still not have the margins ignored?

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android">

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="32dp"
        android:layout_marginRight="32dp"
        android:text="@string/longstring"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

Solution

  • Add the following line in the button xml so that the button respects the margins

    app:layout_constrainedWidth="true"
    

    OUTPUT

    enter image description here