How to put text view in the center of the layout if second Textview visibility is gone?
I have attached a layout that I draw by hand.
I have there two Textview inside lets say ConstraintLayout
I want to write an xml that in situation that there are two visible TextViews sets margin and constraint according to numbers in screenshot but in case TextView2 visibility is gone I want to put TextView1 in the center of the layout.
Can someone help me with that?
<?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/TextView1”
android:layout_width=“100dp”
android:layout_height="wrap_content"
android:text=“TextView”1
app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart=“16dp"
/>
<TextView>
android:id="@+id/TextView2”
android:layout_width=“100dp”
android:layout_height="wrap_content"
android:text=“TextView”1
app:layout_constraintEnd_toEndOf=“parent”
app:layout_constraintStart_toStartOf=“@id/TextView1”
android:layout_marginStart=“20dp"
android:layout_marginEnd“8dp"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
Place the two TextViews in a horizontal chain with the chain style set to spread_inside
. Now, when the right TextView is set to gone, the left TextView assumes the right constraint of the right TextView with a new margin set to 16dp
(app:layout_goneMarginEnd="16dp"
).
See Margins when connected to a GONE widget.
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/TextView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="TextView1"
app:layout_constraintEnd_toStartOf="@+id/TextView2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_chainStyle="spread_inside"
app:layout_goneMarginEnd="16dp" />
<TextView
android:id="@+id/TextView2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:text="TextView2"
app:layout="@id/TextView1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/TextView1"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>