Programmatically set boxBackgroundMode to TextInputLayout

DMan :

I just migrate from com.android.support:design to com.google.android.material.

implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.1.0'

I have the troubles with set up boxBackgroundMode as an outline for TextInputLayout programmatically.

 val textInputLayout = TextInputLayout(this)
 textInputLayout.addView(EditText(this))

 textInputLayout.boxBackgroundMode = TextInputLayout.BOX_BACKGROUND_OUTLINE
 textInputLayout.boxStrokeColor = Color.BLACK
 textInputLayout.boxBackgroundColor = Color.BLACK
 textInputLayout.setBoxCornerRadii(23f,23f,23f,23f)

 someParentLayout.addView(textInputLayout)

At the same time, I hadn't such problems with com.android.support:design. Can someone suggest how to resolve or tell why for com.google.android.material it doesn't work.

P.S. It works by defining style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox" in xml but i need to do it programmatically

azizbekian :

Instead of:

textInputLayout.addView(EditText(this))

Perform:

val editText = EditText(this)
editText.background = null
textInputLayout.addView(editText)
// Alternatively `textInputLayout.addView(EditText(this).apply { background = null })`

Why?

Excerpt from TextInputLayout sources:

  private boolean shouldUseEditTextBackgroundForBoxBackground() {
    // When the text field's EditText's background is null, use the EditText's background for the
    // box background.
    return editText != null
        && boxBackground != null
        && editText.getBackground() == null // <-- by default EditText has background
        && boxBackgroundMode != BOX_BACKGROUND_NONE;
  }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=174956&siteId=1