Search code examples
javaandroidmaterial-designandroid-textinputlayoutmaterial-components-android

Android: Programmatically adding TextInputLayout


I am trying to add a TextInputLayout with an EditText to a LinearLayout programmatically. My approach:

TextInputLayout textInputLayout = new TextInputLayout(new ContextThemeWrapper(getContext(), R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox));
textInputLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textInputLayout.setHintTextAppearance(R.style.Base_Widget_MaterialComponents_TextInputLayout_TextInputLayout);

TextInputEditText editText = new TextInputEditText(getContext());
editText.setHint("test");

textInputLayout.addView(editText, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.addView(textInputLayout);

However, the result looks extremly buggy:

buggy view


Weirdly enough, adding the same TextInputLayout via XML works:

<com.google.android.material.textfield.TextInputLayout
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="kommentar"
    app:hintTextAppearance="@style/Base.Widget.MaterialComponents.TextInputLayout.TextInputLayout">

    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</com.google.android.material.textfield.TextInputLayout>

working view via xml


Now, I need to add that the programmatical approach worked before upgrading to Material 1.1. I am using material components only. How can I fix this?


Solution

  • With the style attribute you have to use setBoxBackgroundMode() method to use OutlineBox style. Beside this, you should have use TextInputLayout's context to create TextInputEditText. Check below:

    textInputLayout.setBoxBackgroundColor(ContextCompat.getColor(getContext(), android.R.color.white));
    textInputLayout.setBoxBackgroundMode(TextInputLayout.BOX_BACKGROUND_OUTLINE);
    
    //Must use context of textInputLayout
    TextInputEditText editText = new TextInputEditText(textInputLayout.getContext());
    

    Output:

    enter image description here