Vadim
Vadim

Reputation: 51

How to hide and show a view with the same button in Kotlin

For an android app I want to hide and show a view with the same button. It's probably a very basic understanding that I'm missing. So I would be really grateful for an explanation.

I've tried the code below, but it's only working once.

if (view1.isVisible){
        btnHideShow.setOnClickListener{
            view1.visibility = View.GONE
            if (view1.isGone) {
                btnHideShow.setOnClickListener {
                    view1.visibility = View.VISIBLE
                }
            }
        }
    }

Upvotes: 0

Views: 1937

Answers (3)

BestUserApps
BestUserApps

Reputation: 1

The accepted answer is incorrect. Correctly:

btnHideShow.setOnClickListener { view1.isVisible = !view1.isVisible }

Upvotes: 0

Madhav
Madhav

Reputation: 351

Simplest way to achieve that

btnHideShow.setOnClickListener{ view1.visibility = !view1.visibility }

Upvotes: 1

Vadim
Vadim

Reputation: 51

Thanks to the comment I found out it's easy like this:

btnHideShow.setOnClickListener{
        if (view1.isVisible){
            view1.visibility = View.GONE
        }
        else view1.visibility = View.VISIBLE
    }

Upvotes: 0

Related Questions