以编程方式将boxBackgroundMode设置为TextInputLayout

时间:2020-03-06 16:01:47

标签: android android-layout android-view android-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"来工作,但我需要以编程方式进行

1 个答案:

答案 0 :(得分:1)

代替:

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;
  }
相关问题