How can I check if a view is visible or not in Android?

AndroidUser InterfaceVisible

Android Problem Overview


I set visibility to invisible like this on Android:

myImageView.setVisibility(View.INVISIBLE);

And then to make it visible:

myImageView.setVisibility(View.VISIBLE);

Now I don't know if myImageView is visible or not, how can I check it like this:

if (myImageView IS VISIBLE) {
    Do something
} else {
    Do something else
}

How can I do that? What do I have to write within the brackets?

Android Solutions


Solution 1 - Android

Although View.getVisibility() does get the visibility, its not a simple true/false. A view can have its visibility set to one of three things.

View.VISIBLE The view is visible.

View.INVISIBLE The view is invisible, but any spacing it would normally take up will still be used. Its "invisible"

View.GONE The view is gone, you can't see it and it doesn't take up the "spot".

So to answer your question, you're looking for:

if (myImageView.getVisibility() == View.VISIBLE) {
    // Its visible
} else {
    // Either gone or invisible
}

Solution 2 - Android

Or you could simply use

View.isShown()

Solution 3 - Android

If the image is part of the layout it might be "View.VISIBLE" but that doesn't mean it's within the confines of the visible screen. If that's what you're after; this will work:

Rect scrollBounds = new Rect();
scrollView.getHitRect(scrollBounds);
if (imageView.getLocalVisibleRect(scrollBounds)) {
    // imageView is within the visible window
} else {
    // imageView is not within the visible window
}

Solution 4 - Android

You'd use the corresponding method getVisibility(). Method names prefixed with 'get' and 'set' are Java's convention for representing properties. Some language have actual language constructs for properties but Java isn't one of them. So when you see something labeled 'setX', you can be 99% certain there's a corresponding 'getX' that will tell you the value.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartinView Question on Stackoverflow
Solution 1 - AndroidWilliamView Answer on Stackoverflow
Solution 2 - AndroiddeviatoView Answer on Stackoverflow
Solution 3 - AndroidBill MoteView Answer on Stackoverflow
Solution 4 - AndroidcolithiumView Answer on Stackoverflow