Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set visibility in Kotlin?

Tags:

android

kotlin

People also ask

How do you set the visibility of a picture in Kotlin?

Setting the visibility using myView. visibility = myVisibility in Kotlin is the same as setting it using myView. setVisibility(myVisibility) in Java. Show activity on this post.

What is visibility modifier in Kotlin?

Visibility modifiers are not exactly new in Android. Kotlin has twisted them a little bit but in general, everything remains the same. The aim of modifiers is facilitating the encapsulation of components and the same good practices apply when using them in Kotlin.


In response to this answer, I believe a Kotlin-styled way to accomplish this can also be written as:

fun showHide(view:View) {
    view.visibility = if (view.visibility == View.VISIBLE){
        View.INVISIBLE
    } else{
        View.VISIBLE
    }
}

if you want to visible icon

 ic_back.visibility = View.VISIBLE

and if you want to visibility GONE so please try it :

ic_back.visibility = View.GONE

You can simply do it.

idTextview.isVisible = true
idTextview.isVisible = false

You could do this in an extension function:

fun View.toggleVisibility() {
    if (visibility == View.VISIBLE) {
        visibility = View.INVISIBLE
    } else {
        visibility = View.VISIBLE
    }
}

Can be used like this:

someView.toggleVisibility()

You can convert using Android Studio: Click on the Java file you want to convert, choose Code -> Convert Java File To Kotlin File and see the magic. The result is:

fun showHide(view: View) {
        if (view.visibility == View.VISIBLE) {
            view.visibility = View.INVISIBLE
        } else {
            view.visibility = View.VISIBLE
        }
    }

A simple way in Kotlin:

fun toggleView(view: View) {
    view.isVisible = !view.isVisible
}