【问题标题】:Custom TextInputLayout自定义文本输入布局
【发布时间】:2020-10-09 06:59:03
【问题描述】:

我想让我的CustomTextInputLayoutWidget.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 设置默认样式?

【问题讨论】:

  • 这是一种风格,而不是主题,这就是为什么它不能按预期使用ContextThemeWrapperTextInputLayout 现在有公开可用的方法来设置该背景,但是,如 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


【解决方案1】:

这不是您正在寻找的。 你可以定义:

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

与:

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

然后在你的布局中使用:

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

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

 </com.example.quicksample.CustomTextInputLayout>

您的代码不起作用,因为ContextThemeWrapper(context, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox)第二个参数必须是属性主题而不是样式(TextInputLayout(context, attrs, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox) 也是如此)

【讨论】:

    猜你喜欢
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多