You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中Kotlin代码的isErrorEnabled属性不生效问题求助

Android Studio中Kotlin代码的isErrorEnabled属性不生效问题求助

问题描述

我正在跟着一个登录注册的教程做,到第3个视频的13:00左右时,发现isErrorEnabled相关的错误提示逻辑不生效,尝试网上搜索但没找到解决办法。

相关代码如下:

RegisterActivity.kt中的validateName方法

private fun validateName(): Boolean{
    var errorMessage: String? = null
    val value: String = mBinding.nameBoxRegister.text.toString()
    if(value.isEmpty()){
        errorMessage = "Full name is required / Se requiere nombre completo"
    }
    if(errorMessage != null){
        mBinding.nameBoxRegister.apply {
            isErrorEnabled = false
            error = errorMessage
        }
    }
}

activity_register.xml中的nameBoxRegister布局

<com.google.android.material.textfield.TextInputLayout
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/nameBoxRegister"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/name_box_register"
        android:inputType="text"
        android:paddingHorizontal="8dp"
        android:paddingVertical="12dp" />
</com.google.android.material.textfield.TextInputLayout>

问题原因

你代码里的逻辑有个明显的小错误:你先把isErrorEnabled设为false,然后再设置error内容。isErrorEnabled是控制TextInputLayout是否显示错误提示的开关,当它为false时,哪怕你设置了错误文本,也不会显示出来。

解决方案

只需要调整代码顺序,或者直接去掉isErrorEnabled = false的设置(因为当你给error赋值非空字符串时,系统会自动把isErrorEnabled设为true)。另外别忘了让方法返回验证结果,不然后续逻辑可能也会出问题。

修正后的代码:

private fun validateName(): Boolean{
    var errorMessage: String? = null
    val value: String = mBinding.nameBoxRegister.text.toString()
    if(value.isEmpty()){
        errorMessage = "Full name is required / Se requiere nombre completo"
    }
    if(errorMessage != null){
        mBinding.nameBoxRegister.apply {
            // 要么改成true,要么直接删掉这行
            isErrorEnabled = true
            error = errorMessage
        }
        // 验证不通过返回false
        return false
    }
    // 验证通过返回true
    return true
}

备注:内容来源于stack exchange,提问作者Gothman 11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 11:14:51