13

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?

StealthDroid
  • 365
  • 1
  • 4
  • 14

5 Answers5

35

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
}
Natan
  • 1,867
  • 13
  • 24
8

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

fun hacerVisibleLaFoto(v: View) {
    imageView.visibility = View.VISIBLE;
}
Bob
  • 13,447
  • 7
  • 35
  • 45
4
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
Pinkesh Darji
  • 1,041
  • 10
  • 23
2

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()
Andrew Steinmetz
  • 1,010
  • 8
  • 16
  • More clean solution: fun View.showOrGone(show: Boolean) { visibility = if(show) View.VISIBLE else View.GONE } – Azarnoy Nov 12 '20 at 11:56
2

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.

Raghib Arshi
  • 717
  • 8
  • 12