Home > Software design >  Set Visibility When Input Happen on EditText - Kotlin
Set Visibility When Input Happen on EditText - Kotlin

Time:08-07

I'm kinda new with Kotlin but i'm trying to make my TextView visibility gone or visible based on the live input on Edit Text. Basically, When the user start to input something, i want this text to visible and when they delete until empty, this text is dissapear. I tried to fix it but i still couldn't found any good results. Anyway, thank you.

this is my code:

        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
        }

 } 

CodePudding user response:

You need to set a listener to check for text changes, rather than getting the current value of the EditText once during setup.

You can do this using the doOnTextChanged method. This would look like:

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
}
  • Related