Search code examples
androidkotlinandroid-themematerial-components-androidandroid-textinputlayout

How set default style for custom TextInputLayout


I want to create au custom TextInputLayout with a default style. But the style isn't applied.

class AutoCompleteTextInputLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = R.style.AppTheme_TextInputLayout_DropdownMenu
): TextInputLayout(context, attrs) {

    init {
        context.inflater.inflate(R.layout.auto_complete_text_input_layout, this,true) 
    }

}
<style name="AppTheme.TextInputLayout.DropdownMenu" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu">
    <item name="endIconMode">dropdown_menu</item>
</style>

<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <AutoCompleteTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</merge>

I don't want this style to be applied by default for all TextInputLayout because I have already one like below:

    <style name="AppTheme" parent="Theme.MaterialComponents.Light">
        <item name="textInputStyle">@style/AppTheme.TextInputLayout</item>>
    </style>

Thanks in advance for your help


Solution

  • You can't use the constructor with R.style.AppTheme_TextInputLayout_DropdownMenu because the 3rd parameter of the TextInputLayout isn't a style but the attribute theme as R.attr.textInputStyle.

    You can use something like:

    public class AutoCompleteTextInputLayout @JvmOverloads constructor(
            context: Context, 
            attrs: AttributeSet? = null, 
            defStyleAttr: Int = R.attr.textInputStyle
    ) : TextInputLayout(ContextThemeWrapper(context, R.style.Custom_Theme),
                        attrs, defStyleAttr) { ...  }
    

    with a custom theme:

    <style name="Custom.Theme" parent="">
       <item name="textInputStyle">@style/AppTheme.TextInputLayout.DropdownMenu</item>
    </style>
    

    In this way you are creating a new context wrapper with the specified theme (Custom.Theme). This theme is used only by the custom widget AutoCompleteTextInputLayout.
    It means that the other TextInputLayouts continue to use the default style (defined by the attribute textInputStyle in the AppTheme).

    Example:

    <AutoCompleteTextInputLayout>
    
        <com.google.android.material.textfield.TextInputEditText/>
    
    </AutoCompleteTextInputLayout>
    
    <com.google.android.material.textfield.TextInputLayout>
    
         <com.google.android.material.textfield.TextInputEditText/>
    
    </com.google.android.material.textfield.TextInputLayout>
    

    enter image description here