Search code examples
androidandroid-constraintlayout

ConstraintLayout how to align to center of screen and not to overlap uneven side buttons


I have a design request to make a text be the center of the screen but not to overlap buttons on the sides. those buttons might appear or not. This is the design:this is the design

The problem is when the text is long, this bad thing happens: bad But I want it to be like this: good


Solution

  • You can use Guideline for this:

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    
    
    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.4"/>
    
    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.6"/>
    
    <View
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:background="@android:color/holo_blue_light"
        app:layout_constraintEnd_toStartOf="@+id/guideline1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    
    <View
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        app:layout_constraintStart_toEndOf="@id/guideline2"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:background="@android:color/holo_blue_light"/>
    
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="sjkelf hue hwe fhwefh wehwe hwe hwef "
        app:layout_constraintStart_toEndOf="@id/guideline1"
        app:layout_constraintEnd_toStartOf="@id/guideline2"
        app:layout_constraintTop_toTopOf="parent"/>
    
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    It looks like this:

    enter image description here