Android.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET: 非活动类的TextInputLayout的风格化

问题描述 投票:0回答:1

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

下面是示例代码。

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)

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

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

任何帮助都是非常感激的,谢谢。

android android-textinputlayout
1个回答
1
投票

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


0
投票

用上下文包装器设置TextInputLayout样式,我想应该可以。

val textInputLayout = TextInputLayout(
        ContextThemeWrapper(
            this,
            R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox
        )
    )
© www.soinside.com 2019 - 2024. All rights reserved.