Lisa Baron
Lisa Baron

Reputation: 71

What do I do if I want to hide a button AFTER it is tapped?

What do I do if I want to hide "CHANGE TEXT" button AFTER it is tapped? From Android Kotlin Fundamentals: Add user interactivity

  1. Hide the DONE button by setting the visibility property to View.GONE. You already have the button's reference as the function's input parameter, view.

view.visibility = View.GONE

I try to follow that and the "CHANGE TEXT" button disappears before I tap the "CHANGE TEXT" button which is not what I want.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main) //set the layout
        val simpleTextView =
            findViewById<View>(R.id.simpleTextView) as TextView //get the id for TextView
        val changeText = findViewById<View>(R.id.btnChangeText) as Button //get the id for button
        changeText.visibility = View.GONE        
changeText.setOnClickListener {
            simpleTextView.text = "After Clicking" //set the text after clicking button
        }
    }
}

Should be like this before the button is tapped. Should be like this before the button is tapped2

However, the result is like this instead. \n enter image description here3

Upvotes: 1

Views: 135

Answers (1)

Mayur Gajra
Mayur Gajra

Reputation: 9083

You've just misplaced your changeText.visibility = View.GONE

it should be inside changeText.setOnClickListener

So your code would look like this:

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val simpleTextView =
            findViewById<TextView>(R.id.simpleTextView) as TextView //get the id for TextView
        val changeText = findViewById<View>(R.id.btnChangeText) as Button //get the id for button
        changeText.setOnClickListener {
            simpleTextView.text = "After Clicking" //set the text after clicking button
            changeText.visibility = View.GONE //it should be here
        }

    }


}

Upvotes: 2

Related Questions