Jan Żankowski
Jan Żankowski

Reputation: 8941

In an Android test, how to check that a View is shown?

I'm writing a UI test case (using ActivityUnitTestCase) and would like to check if at a given time a View subclass is visible to the user. I've found the View#isShown() method, which claims to do exactly this - checking the visibility field of this element and all its parents - but somehow it always returns "false" for all the elements. I'll be grateful for some help. If it makes it easier, I can paste some code.

Also, I found ViewAsserts#assertOnScreen(View origin, View view) but it doesn't seem to do the right thing either - always returns true. Am I perhaps calling it wrong: assertOnScreen(viewImTesting.getRootView(), viewImTesting)?

Thanks, Jan

Upvotes: 4

Views: 5194

Answers (3)

Diego Torres Milano
Diego Torres Milano

Reputation: 69198

Try using

final View origin = activityImTesting.getWindow().getDecorView();
android.test.ViewAsserts.assertOnScreen(origin, viewImTesting);

Upvotes: 0

yjw
yjw

Reputation: 3444

Maybe this is too late? Just for triggering some response from @dtmilano and other Android experts, there seems to be some differences in interpretation of visibility "gone".

While visibility=gone is listed as if a view is completely not added, this definition is probably closer to the truth. I realise it is actually still on the screen with a x and y coordinate, but the width and height will be 0.

And when I dig into ViewAsserts.java, assertOnScreen() is only concerned with the y coordinate of the view in the origin, ensuring it is bigger than 0 but not more than the height of the origin.

To conclude: assertOnScreen is probably not the right method to use if you are testing for the visibility of a view, which I suppose is what you are trying to do based on your question.

Hope the above information is of use (and correct)!

Upvotes: 0

Jan Żankowski
Jan Żankowski

Reputation: 8941

I found a sensible workaround: just checking View#getVisibility() against View#VISIBLE, VIEW#INVISIBLE, or VIEW#GONE.

This probably doesn't work when e.g. a parent view is not visible but this one has visibility set to VISIBLE, but for most cases it should suffice.

Upvotes: 3

Related Questions