Programmatically set boxBackgroundMode to TextInputLayout

别来无恙 提交于 2021-01-28 20:21:03

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/60567668/programmatically-set-boxbackgroundmode-to-textinputlayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!