Custom TextInputLayout does not apply correct styling with default constructor

Viewed 53

I've created two examples of code in which one is applying the correct styling to the TextInputLayout and the other is not. I would like to understand why this is happening. In my eyes they should be exactly the same. The only difference is whether I define the constructor as primary or secondary constructor. In both cases I call the 3 argument constructor of the super.

This applies the correct styling to the TextInputLayout:

class CustomTextInputLayout : TextInputLayout {

// Primary constructor does not apply correct styling i.c.m. ContextThemeWrapper
@JvmOverloads
constructor(
    context: Context,
    attrs: AttributeSet? = null,
    @AttrRes defStyleAttr: Int = com.google.android.material.R.attr.editTextStyle,
    @StyleRes defStyleRes: Int = com.google.android.material.R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox
) : super(ContextThemeWrapper(context, defStyleRes), attrs, defStyleAttr)

private val layout: TextInputLayout = this
private val edit: TextInputEditText = TextInputEditText(context)

init {
    addEditBox(edit)
    layout.hint = "This is the hint"
}

private fun addEditBox(editText: TextInputEditText) {
    val layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
    editText.layoutParams = layoutParams
    addView(editText)
}

This DOES NOT apply the correct styling to the TextInputLayout:

class CustomTextInputLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    @AttrRes defStyleAttr: Int = com.google.android.material.R.attr.editTextStyle,
    @StyleRes defStyleRes: Int = com.google.android.material.R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox
) : TextInputLayout(ContextThemeWrapper(context, defStyleRes), attrs, defStyleAttr) {

private val layout: TextInputLayout = this
private val edit: TextInputEditText = TextInputEditText(context)

init {
    addEditBox(edit)
    layout.hint = "This is the hint"
}

private fun addEditBox(editText: TextInputEditText) {
    val layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
    editText.layoutParams = layoutParams
    addView(editText)
}

I hope that someone can explain to me why I need to define it as secondary constructor. Or provide a solution where the styling is applied with a primary constructor.

0 Answers
Related