Damian Walker

Personal Web Pages

An Invisible ImageView Peculiarity

Friday, 26th June 2015

This morning I had a little bit of difficulty with a custom ImageView on a new project. The image wasn't being displayed at all. In fact, putting "Toast" messages in the onDraw method to inspect the running revealed that the onDraw method wasn't being called at all!

The bitmap in this view isn't loaded from a png, but generated at runtime; it's a game board, and its content comes from a conceptual board object (currently empty, but at least I should see the empty squares). I checked this against an existing project of mine which has never experienced this difficulty, and found no relevant differences in the Java code.

Finally I re-checked the XML and found the error. The old project referenced a dummy PNG file in the "android:src" attribute of the view. When building the new project, I had wondered if this was really necessary, given that I discard it immediately and rebuild the view's contents in the onDraw method.

It turns out that it is necessary to have a dummy image in the "android:src" attribute. Without it, it seems that the view is never drawn. The only reason I can think of is that the system needs an image to calculate the view's ratio of x:y dimensions. It certainly doesn't use it to calculate the pixel size, as my 240x240 image is replaced by a canvas the full 540-pixel width of my screen.

I need to look further into this to see if there's a neater way to allow my view to be generated and shown. But until then, I'll have to continue to stick with a dummy image to get things working.