StealthDroid
StealthDroid

Reputation: 385

Android Kotlin .visibility

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?

Upvotes: 13

Views: 30004

Answers (5)

Raghib Arshi
Raghib Arshi

Reputation: 755

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.

Upvotes: 2

Andrew Steinmetz
Andrew Steinmetz

Reputation: 1049

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()

Upvotes: 2

Pinkesh Darji
Pinkesh Darji

Reputation: 1111

View.VISIBLE 

Should go after the = sign to make the value visible. It has integer constant value in View class. You can check it by pressing ctrl + click (Windows) or cmd + click (Mac).

So it should be like this.

imageView.visibility = View.VISIBLE

Upvotes: 4

Natan
Natan

Reputation: 1885

Android has static constants for view visibilities. In order to change the visibility programmatically, you should use View.VISIBLE, View.INVISIBLE or View.GONE.

Setting the visibility using myView.visibility = myVisibility in Kotlin is the same as setting it using myView.setVisibility(myVisibility) in Java.

In your case:

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

Upvotes: 35

Bob
Bob

Reputation: 13865

Use View.VISIBLE. That is a constant defined in View class.

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

Upvotes: 8

Related Questions