以编程方式将boxBackgroundMode设置为TextInputLayout

问题描述 投票:0回答:2

我只是从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"来工作,但我需要以编程方式进行]
android material-ui android-textinputlayout
2个回答
0
投票
而不是:

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


-1
投票
您需要使用TextInputLayout.setBoxBackgroundMode()方法来使用OutlineBox样式

setBoxBackgroundMode(int boxBackgroundMode)

设置框背景的模式(填充,轮廓或无)。然后,您需要使用TextInputLayout.BOX_BACKGROUND_OUTLINE)常量

要获得TextInputLayout的OutlineBox的角落,您需要使用setBoxCornerRadii()方法。基于此:how to set the Style Attribute Programmatically in Android?当前不支持动态样式更改。您必须先设置样式,然后再创建视图(以XML格式)。

© www.soinside.com 2019 - 2024. All rights reserved.