Android Kotlin .visibility

Viewed 27615

I have this code that is supposed to make an image visible, but I don't know exactly how it's supposed to be written for Kotlin.

I'm trying to use .visibility in Kotlin, and I don't know what to give it for a value. It's based off of setVisibility().

Code:

fun hacerVisibleLaFoto(v: View) {
    imageView.visibility = 1;
}

I put 1 in the value spot because an integer value is required there, and that's my placeholder value until I find what really goes there.

What should go after the = sign to make the value visible?

5 Answers

Taking advantage of some of Kotlin's language features, I use these two extension methods on View that toggle the visibility with a boolean as a convenience.

fun View.showOrGone(show: Boolean) {
    visibility = if(show) {
        View.VISIBLE
    } else {
        View.GONE
    }
}

fun View.showOrInvisible(show: Boolean) {
    visibility = if(show) {
        View.VISIBLE
    } else {
        View.INVISIBLE
    }
}

Basic usage:

imageView.showOrGone(true) //will make it visible
imageView.showOrGone(false) //will make it gone

Although if you are looking for just a little syntactic Kotlin sugar to make your View visible, you could just write an extension function like so to make it visible.

fun View.visible() {
    visibility = View.Visible
}

Basic usage:

imageView.visible()

Very easy and simple

To visible a view :

ViewName.visibility = View.VISIBLE

e.g.- button.visibity = View.VISIBLE

To invisible a view :

ViewName.visibility = View.INVISIBLE

e.g.- button.visibity = View.INVISIBLE

Anything you can use like button, textview, image view etc

Hope this would work.

Related