Search code examples
androidandroid-layoutmaterial-designandroid-custom-viewmaterial-components-android

How to do Filled and Outlined at the same time TextInputLayout android?


I used <com.google.android.material.textfield.TextInputLayout but I will also accept other options or libs

Expected result:

focused: focused
unfocused: unfocused


Solution

  • You can achieve this using a custom TextInputLayout Style which inherits from Widget.MaterialComponents.TextInputLayout.FilledBox and a custom background selector for TextInputEditText.

    Create the TextInputLayout in xml like below:

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/emailTextInputLayout"
        style="@style/MyTextInputLayoutStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
    
        <com.google.android.material.textfield.TextInputEditText
           android:id="@+id/emailTextInputEditText"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:background="@drawable/edit_text_background"
           android:hint="Email"
           android:importantForAutofill="no"
           android:singleLine="true" />
    </com.google.android.material.textfield.TextInputLayout>
    

    where @style/MyTextInputLayoutStyle is a custom style which inherits from Widget.MaterialComponents.TextInputLayout.FilledBox like below:

    <style name="MyTextInputLayoutStyle" parent="Widget.MaterialComponents.TextInputLayout.FilledBox">
       <item name="boxBackgroundColor">@android:color/transparent</item>
       <item name="boxStrokeWidth">0dp</item>
       <item name="boxStrokeWidthFocused">0dp</item>
       <item name="hintTextColor">#7d8b9f</item>
    </style>
    

    and @drawable/edit_text_background is a Drawable Selector to change the background based on the default and focused states like below:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_focused="true">
            <shape android:shape="rectangle">
                <solid android:color="#f0f5fa"/>
                <stroke android:width="2dp" android:color="#b5c3f6"/>
                <corners android:radius="10dp"/>
            </shape>
        </item>
        <item>
            <shape android:shape="rectangle">
                <solid android:color="#f0f5fa"/>
                <stroke android:width="0dp" android:color="#b5c3f6"/>
                <corners android:radius="10dp"/>
            </shape>
        </item>
    </selector>
    

    Results will be like below:

    focused unfocused