Search code examples
kotlinbuttontextviewvisibility

Set textview visibility based on button click in Kotlin


Using Kotlin, I would like to be able to have an invisible Textview become visible on my activity when the user clicks a button. Ideally, I would like them to enter a particular code (i.e 1234) into a plain textview field (id PW1) then click the submit button (id sub1), then I would like a hidden textview (id phone1) to appear to allow the user to enter some more data.

Any help greatly appreciated

Many thanks Please see code below...App runs but crashes when I go to the activity with this code.

val sub1 =findViewById<Button>(R.id.sub1)
sub1.setOnClickListener {
val pw1: String = pw1.text. toString()
if (pw1.equals( "1234"))
phone1.visibility = View.VISIBLE
else phone1.visibility = View.INVISIBLE }

Solution

  • Give your view an ID, by adding android:id="@+id/myTextView" in your XML tag.

    Then, all you have to do, is run myTextView.visibility = View.VISIBLE or myTextView.visibility = View.HIDDEN or myTextView.visibility = View.GONE to change its state.

    • VISIBLE will show the view
    • HIDDEN will hide it but it'll still have the space for that element reserved
    • GONE will hide it as if it was completely unexistant.

    Your example states that you want on button click; add an ID to the button, and in your onCreate function in your Activity, add an onclicklistener:

    myButton.setOnClickListener {
      // your code here
      myTextView.visibility = 
        if (condition) View.VISIBLE
        else View.HIDDEN
    }
    

    Some more techniques on how to achieve this in this question : How to set visibility in Kotlin?