Custom TextInputLayout

Viewed 727

I want to have my CustomTextInputLayout to have Widget.MaterialComponents.TextInputLayout.OutlinedBox as default style without defining it anywhere in the XML.

I tried this

class CustomTextInputLayout @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : TextInputLayout(ContextThemeWrapper(context, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox), attrs, defStyleAttr) {

}

and this

class CustomTextInputLayout @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : TextInputLayout(context, attrs, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox)

but it's not working. I've tried the default XML way

<com.custom.CustomTextInputLayout
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    ...>
    <com.google.android.material.textfield.TextInputEditText
        ...
        android:hint="Sample Hint" />
</com.custom.CustomTextInputLayout>

and it's working.

  • What am I missing here?
  • How can I set a default style for custom TextInputLayout without using XML?
1 Answers

It is not exactly what you are looking for. You can define:

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

with:

<style name="Outlined.Theme" parent="">
      <item name="textInputStyle">@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox</item>
</style>

Then in your layout juse use:

 <com.example.quicksample.CustomTextInputLayout
       ....
       android:hint="Sample">

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

 </com.example.quicksample.CustomTextInputLayout>

enter image description here

Your code doesn't work because ContextThemeWrapper(context, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox) the 2nd parameter has to be an attribute theme and not a style (it is the same for TextInputLayout(context, attrs, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox))

Related