androidandroid-layoutandroid-textinputlayoutandroid-textinputedittext

How to add Different Padding Between Floating Hint and Input Text in Custom TextInputLayout?


I'm working on a custom TextInputLayout in my Android project. I need to differentiate the padding between the floating hint (label) and the input text. When the hint is floating (acting as a label), it should have a padding of 0dp, but the input text should have a padding of 12dp. Here is the visual representation of what I'm trying to achieve:

enter image description here

I've tried to set different paddings for the hint and the input text, but both end up with the same padding. Any guidance on how to achieve this would be greatly appreciated. Thank you!


Solution

  • What you are asking to do does not seem to be part of the API. You can, however, get the effect you want by adding a clear start drawable to the TextInputEditText.

    square.xml

    <shape 
        android:shape="rectangle">
        <solid android:color="@android:color/transparent" />
        <size
            android:width="12dp"
            android:height="0dp" />
    </shape>
    
    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp">
    
        <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="This is a hint"
            android:paddingTop="16dp">
    
            <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:drawableStart="@drawable/square"
                android:paddingStart="0dp"
                android:textColor="@color/black" />
    
        </com.google.android.material.textfield.TextInputLayout>
    
        <EditText
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp" />
    </androidx.appcompat.widget.LinearLayoutCompat>
    

    The start drawable will push entered text 12dp to the right while the hint will ignore it.

    enter image description here

    You may also use the start icon for the TextInputLayout:

    app:startIconDrawable="@drawable/square"
    app:startIconMinSize="12dp"
    

    Although, you may already have a start icon.