me.at.coding
me.at.coding

Reputation: 17724

Baseline align spinner to TextInputLayout in ConstraintLayout

I need to baseline align a Spinner to an TextInputLayout in ConstraintLayout. This is my xml:

<?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"
tools:context=".MainActivity">


<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/textInputLayout"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="hint" />
</com.google.android.material.textfield.TextInputLayout>

<Spinner
    android:id="@+id/spinner"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginLeft="16dp"
    android:entries="@array/spinner_values"
    app:layout_constraintStart_toEndOf="@id/textInputLayout"
    app:layout_constraintBaseline_toBaselineOf="@id/textInputLayout"

    />

Values for @array/spinner_values:

<string-array name="spinner_values">
    <item>hello</item>
</string-array>

and this is the result: enter image description here

Obviously the Spinner baseline is not aligned with the baseline of the TextInputLayout. How can I fix this?

Upvotes: 0

Views: 570

Answers (1)

Mehul Kabaria
Mehul Kabaria

Reputation: 6622

Basically TextInputLayout does not providing Baseline with its parent layout. Try below it may help you.

public class CustomTextInputLayout extends TextInputLayout {

    public CustomTextInputLayout(Context context) {
        super(context);
    }

    public CustomTextInputLayout(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
    }

    public CustomTextInputLayout(Context context, AttributeSet attributeSet, int defStyleAttr) {
        super(context, attributeSet, defStyleAttr);
    }

    @Override
    public int getBaseline()
    {
        EditText editText = getEditText();
        return editText.getPaddingTop() + editText.getBaseline();
    }
}

Upvotes: 1

Related Questions