【发布时间】:2020-10-09 06:59:03
【问题描述】:
我想让我的CustomTextInputLayout 将Widget.MaterialComponents.TextInputLayout.OutlinedBox 作为默认样式无需在 XML 中的任何位置定义它。
我试过了
class CustomTextInputLayout @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : TextInputLayout(ContextThemeWrapper(context, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox), attrs, defStyleAttr) {
}
还有这个
class CustomTextInputLayout @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : TextInputLayout(context, attrs, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox)
但它不起作用。我已经尝试过默认的 XML 方式
<com.custom.CustomTextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
...>
<com.google.android.material.textfield.TextInputEditText
...
android:hint="Sample Hint" />
</com.custom.CustomTextInputLayout>
它正在工作。
- 我在这里缺少什么?
- 如何在不使用
XML的情况下为自定义TextInputLayout设置默认样式?
【问题讨论】:
-
这是一种风格,而不是主题,这就是为什么它不能按预期使用
ContextThemeWrapper。TextInputLayout现在有公开可用的方法来设置该背景,但是,如 this answer 的第一部分所述。您可以在自定义View的初始设置中改为这样做。 -
@MikeM。我试过了,但如output image 所示,左上角被损坏了。 XML 方式可行,但我的要求是不使用 XML。
-
我无法重现:i.stack.imgur.com/j3T2G.png。您使用的是哪个版本的 Material Components?
-
我使用的是
v1.3.0-alpha01,这里是reproducible link -
好吧,在 Kotlin 类中,显然这在
init()块中不起作用,即使使用post()。您必须从显式构造函数中执行此操作。如果您摆脱ContextThemeWrappers,并在需要的地方添加setBoxBackgroundMode(),Java 就可以工作。请记住,从布局 XML 膨胀的Views 是使用两参数构造函数实例化的,因此请确保至少在此处调用它,因为您没有链接构造函数。
标签: android android-textinputlayout material-components-android material-components