androidxaml

How to align one TextView to the start and another to the end on my ConstraintLayout in Android XML?


I'm working on an Android settings screen and I want to create a header layout where two TextViews appear on the same row, DSA aligned to the start (left) The other (Strix) aligned to the end (right)

I'm using a ConstraintLayout for the header, but both texts are stacking or overlapping by default.

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/header"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/windowBackground">

    <TextView
        android:id="@+id/dsa"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DSA"
        android:textSize="24sp"
        android:textStyle="bold"
        android:padding="16dp"
        android:background="?attr/colorSurface" />

    <TextView
        android:id="@+id/strix"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Strix"
        android:textSize="24sp"
        android:textStyle="bold"
        android:padding="16dp"
        android:background="?attr/colorSurface" />
</androidx.constraintlayout.widget.ConstraintLayout>

I thought using ConstraintLayout would automatically place them in a row, but without constraints it just stacks them or shows them incorrectly, How do I fix this?


Solution

  • You need to add proper constraints to each TextView inside the ConstraintLayout.

    It should look something like this:

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?android:attr/windowBackground">
    
        <TextView
            android:id="@+id/dsa"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="DSA"
            android:textSize="24sp"
            android:textStyle="bold"
            android:padding="16dp"
            android:background="?attr/colorSurface"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent" />
    
        <TextView
            android:id="@+id/strix"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Strix"
            android:textSize="24sp"
            android:textStyle="bold"
            android:padding="16dp"
            android:background="?attr/colorSurface"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>