Could someome explain me why android:layout_marginBottom
doesn't work in a Spinner?:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:id="@+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginBottom="20dp"/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/spinner2" />
</androidx.constraintlayout.widget.ConstraintLayout>
It doesn't matter if I use android:layout_marginBottom
or android:layout_margin
. However, If I use android:layout_margin
it adds top, right and left margin. Why the only margin that does't work is the bottom?
Thanks.
The problem is not about Spinner
specifically - if you use two TextView
s the behavior stays the same.
Some observations on "why" and "how":
the Spinner
top and start is constrained to the top and start of the parent ViewGroup
. Since you don't specify a bottom (or end) constraint, a bottom margin is meaningless
the TextView on the other hand has a top constraint - if you let it have a top margin, this will have the desired effect.
Now you could say "well, then I'll just add the bottom constraint to the Spinner
". Unfortunately this is not enough (and here I really don't know why the ConstraintLayout
solver decides to ignore the margin...)
If you want to set a margin to the Spinner
, then the two View
s have to belong to a complete vertical chain:
parent top <- Spinner <-> TextView -> parent bottom
<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">
<Spinner
android:id="@+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@+id/textView"
android:layout_marginBottom="20dp"
app:layout_constraintVertical_bias="0"
app:layout_constraintVertical_chainStyle="packed"/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/spinner2"
app:layout_constraintBottom_toBottomOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>