0

I want to create a TextInputLayout with border using the style: R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox from a non activity class.

Below is sample code:

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);

When I run this I get following crash:

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)

My guess is I'm not able to set the style attribute: R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox to TextInputLayout from the non activity class.

If I remove the call setBoxCornerRadii, the TextInputLayout is shown correctly in my activity but without the box. I need TextInputLayout to show with the box.

Any help is greatly appreciated. Thanks.

Ashish Khurange
  • 903
  • 7
  • 17
  • Why don't you pass an activity context into this class? – einUsername Apr 25 '20 at 13:26
  • 1
    I get the same error with an activity context too. I don't think that's it. I think it's a bug. Check these links. https://github.com/material-components/material-components-android/issues/1192 https://stackoverflow.com/questions/60567668/programmatically-set-boxbackgroundmode-to-textinputlayout – einUsername Apr 25 '20 at 13:40

2 Answers2

1

The problem is that you have not added the view to any layout yet, just created it. Move call to setradius to after addView(), and the problem wil be fixed.

0

set TextInputLayout style with context wrapper I think it should work.

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