【问题标题】:Android: Style TextInputLayout from non Activity classAndroid:来自非 Activity 类的样式 TextInputLayout
【发布时间】:2020-04-25 09:50:00
【问题描述】:

我想使用非活动类中的 R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox 样式创建一个带边框的 TextInputLayout。

下面是示例代码:

TextInputLayout textInputLayout = new TextInputLayout(context, null, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox);

textInputLayout.setHint("My Hint");
textInputLayout.setBoxBackgroundMode(TextInputLayout.BOX_BACKGROUND_OUTLINE);
textInputLayout.setBoxCornerRadii(5, 5, 5, 5);
TextInputEditText et = new TextInputEditText(textInputLayout.getContext());
textInputLayout.addView(et);

当我运行它时,我得到以下崩溃:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.tsp.bonw, PID: 10121
    java.lang.NullPointerException: Attempt to invoke virtual method 'float com.google.android.material.shape.MaterialShapeDrawable.getTopLeftCornerResolvedSize()' on a null object reference
        at com.google.android.material.textfield.TextInputLayout.setBoxCornerRadii(TextInputLayout.java:938)

我的猜测是我无法将样式属性:R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox 从非活动类设置为 TextInputLayout。

如果我删除调用 setBoxCornerRadii,TextInputLayout 会在我的活动中正确显示,但没有框。我需要 TextInputLayout 与框一起显示。

非常感谢任何帮助。 谢谢。

【问题讨论】:

标签: android android-textinputlayout


【解决方案1】:

问题是您还没有将视图添加到任何布局中,只是创建了它。 将 setradius 的调用移到 addView() 之后,问题将得到解决。

【讨论】:

    【解决方案2】:

    使用上下文包装器设置 TextInputLayout 样式我认为它应该可以工作。

    val textInputLayout = TextInputLayout(
            ContextThemeWrapper(
                this,
                R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox
            )
        )
    

    【讨论】:

    • API是从非活动类中使用的,所以不能使用“this”。我试过这个解决方案,它不起作用。
    • 那么也许可以传递你的“上下文”变量?
    • 是的,仅通过上下文测试。
    • 第一次它本身必须使用上下文运行,但它不起作用。传递“this”代码将无法编译。
    猜你喜欢
    • 1970-01-01
    • 2021-04-19
    • 2020-01-08
    • 1970-01-01
    • 2020-12-17
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多