Ashish Khurange
Ashish Khurange

Reputation: 923

Android: Style TextInputLayout from non Activity class

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.

Upvotes: 0

Views: 172

Answers (2)

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.

Upvotes: 1

Bacho Kurtanidze
Bacho Kurtanidze

Reputation: 605

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

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

Upvotes: 0

Related Questions