以编程方式将 boxBackgroundMode 设置为 TextInputLayout

Programmatically set boxBackgroundMode to TextInputLayout

我刚刚从 com.android.support:design 迁移到 com.google.android.material.

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

我无法以编程方式将 boxBackgroundMode 设置为 TextInputLayout 的大纲。

 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)

同时,我在 com.android.support:design 中没有这样的问题。 有人可以建议如何解决或告诉为什么 com.google.android.material 它不起作用。

P.S。它通过在 xml 中定义 style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox" 来工作,但我需要以编程方式进行

而不是:

textInputLayout.addView(EditText(this))

执行:

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

为什么?

摘自 TextInputLayout 来源:

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