首页 > 解决方案 > 如何在自定义 textinputlayout 中修复背景红色

问题描述

Textinputlayout发生错误时,在提供自定义背景以编辑文本后,背景显示为红色。

我正在使用自定义 textinputlayout 进行放置app:hintEnabled="false"

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toRightOf="@+id/tvFirstNameSecondTest"
    app:layout_constraintRight_toRightOf="parent"
    android:id="@+id/tilLastNameSecondTest"
    app:layout_constraintHorizontal_weight="1"
    app:hintEnabled="false"
    android:layout_marginTop="8dp"
    android:layout_marginStart="@dimen/margin_4dp"
    android:layout_marginEnd="@dimen/margin_16dp"
    app:layout_constraintTop_toBottomOf="@+id/tvFirstNameThirdTest">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_form_filling"
        android:id="@+id/etTilLastNameSecondTest"/>
</com.google.android.material.textfield.TextInputLayout>

我的 Kotlin 文件

class FarmerForm : AppCompatActivity() {

lateinit var context: Context
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_farmer_form)
    setSupportActionBar(toolbar)
    context = this
    val updateProfileValidation = AwesomeValidation(ValidationStyle.TEXT_INPUT_LAYOUT)
    updateProfileValidation.addValidation(
        this,
        R.id.tilFirstNameFirstTest,
        RegexTemplate.NOT_EMPTY,
        R.string.txt_enter_valid_name
    )
    btnRegister.setOnClickListener {
        if(updateProfileValidation.validate()){
            Toast.makeText(this, "Form Validated Successfully", Toast.LENGTH_LONG).show();
        }else {
            if(tilFirstNameFirstTest.error!=null){
                etTilFirstNameFirstTest.background = resources.getDrawable(R.drawable.bg_form_error)
            }
        }
    }
}

可绘制的 XML 文件

<shape
xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/colorWhite"/>
<corners android:radius="@dimen/margin_4dp"/>
<stroke
    android:width="2dp"
    android:color="#ff0000"/>
<padding
    android:left="8dp"
    android:top="10dp"
    android:bottom="10dp"
    android:right="8dp"/>

如何修复此错误。

标签: androidandroid-edittextandroid-textinputlayoutmaterial-componentsmaterial-components-android

解决方案


要更改填充文本字段的背景颜色,您可以:

  • 设置boxBackgroundColor你的属性TextInputLayout
  • 使用方法textInputLayout.setBoxBackgroundColorResource()textInputLayout.setBoxBackgroundColor()

TextInputLayout还可以使用以下方法更改笔划:

  • textInputLayout.setBoxCornerRadii()改变拐角半径
  • textInputLayout.setBoxStrokeColor()改变描边的颜色

最后使用com.google.android.material.textfield.TextInputEditText而不是EditText.


推荐阅读