Home » Android » imageview – Android Kotlin .visibility

imageview – Android Kotlin .visibility

Posted by: admin May 14, 2020 Leave a comment

Questions:

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?

How to&Answers:

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
}

Answer:

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

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

Answer:

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

Answer:

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

Answer:

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.