我对Kotlin有点陌生,但我正试图根据Edit Text上的实时输入使我的TextView可见性消失或可见。基本上,当用户开始输入某些内容时,我希望此文本可见,当他们删除到空时,此文本将不可见。我试着修复它,但仍然找不到任何好的结果。不管怎样,谢谢你。
这是我的代码:
val Email = findViewById<EditText>(R.id.EmailBox)
val sEmail = Email.text.toString()
val Password = findViewById<EditText>(R.id.PasswordBox)
val sPassword = Password.text.toString()
val emailtext = findViewById<TextView>(R.id.EmailText)
val passwordtext = findViewById<TextView>(R.id.PasswordText)
if(sEmail.isEmpty()) {
emailtext.visibility = View.VISIBLE
} else if (sPassword.isEmpty()) {
passwordtext.visibility = View.VISIBLE
} else {return
}
}
您需要设置一个侦听器来检查文本更改,而不是在设置过程中获取EditText的当前值一次。
您可以使用doOnTextChanged
方法来执行此操作。这看起来像:
val email = findViewById<EditText>(R.id.EmailBox)
val emailtext = findViewById<TextView>(R.id.EmailText)
// This will hide "emailtext" when "email" is empty, and show
// it when it is not empty
email.doOnTextChanged { newText, _, _, _ ->
emailtext.visibility = if (newText.isNullOrEmpty()) View.INVISIBLE
else View.VISIBLE
}