Home > front end >  How to place two texts in the middle, but so that the location depends on their length
How to place two texts in the middle, but so that the location depends on their length

Time:11-12

I need to limit the position of the TextView, depending on how much space it takes up (example in the screenshot below)

enter image description here

As you can see, in the left example, the Title is quite short, so both TextView are located in the middle.

In the case like the example on the right, the Title takes up a lot of space and goes up, but the Description goes down, but both TextView still remain in the middle. How can I do this using ConstraintLayout?

P.S.: Do not pay attention to the fact that I did not accurately draw examples, I used Paint :)

CodePudding user response:

You'd need to chain both TextViews as "packed" to make both in the middle of the height. This would be applied to the top TV.

This also requires to constraints both TextViews to one another, the top TV to the screen top end, and the bottom TV to the screen bottom end.

As the top TV would be lengthy, you'd constraint its height using layout_constrainedHeight attribute so that you guarantee it won't go beyond the top screen end, or not to be greedy on the bottom TV.

Here it's assumed that the bottom TV text is short or it would be greedy on the top TV otherwise.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@ id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/long_text"
        app:layout_constrainedHeight="true"
        app:layout_constraintBottom_toTopOf="@ id/description"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed" />

    <TextView
        android:id="@ id/description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="description"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="@ id/title"
        app:layout_constraintTop_toBottomOf="@ id/title" />


</androidx.constraintlayout.widget.ConstraintLayout>
  • Related