子类TextInputLayout使用损坏的主题

问题描述

我需要继承TextInputLayout来提供自定义行为。但是,即使主体是空的,布局也会从某个地方拾取不同的主题。如果我能够覆盖主题,我不会太担心,但是该主题只是直截了当,例如错误drawable将不会显示

香草布局:

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/login_username_input_layoutz"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/login_username_hint">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/login_username_input_textz"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

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

enter image description here


子类别的布局:

import android.content.Context
import android.util.AttributeSet
import com.google.android.material.textfield.TextInputLayout

class CustomTextInputLayout @JvmOverloads constructor(
    context: Context,attrs: AttributeSet? = null,defStyleAttr: Int = 0
) : TextInputLayout(context,attrs,defStyleAttr) {}

            <somepackage.CustomTextInputLayout
                android:id="@+id/login_username_input_layoutz"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/login_username_hint">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/login_username_input_textz"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

            </somepackage.CustomTextInputLayout >

enter image description here


材料设计导入:com.google.android.material:material:1.2.0

父级应用主题Theme.MaterialComponents.Light.NoActionBar

解决方法

在构造函数中,使用defStyleAttr: Int = R.attr.textInputStyle代替defStyleAttr: Int = 0