Android ListView Contents Disappearing
Posted by error454 on 08/03/2012
Sometimes you encounter issues on Android that seem so blatantly simple, you can’t imagine that you are the first person to have hit them. This seemed like a simple case where my TextView items were not being rendered “sometimes” when I scrolled my ListView.
Stackoverflow to the Rescue
In typical programmer fashion, this is the first place I turned where I found that I was in good company. Unfortunately all of the people encountering the issue on SO had been hiding elements in their List and were forgetting to unhide them. I wasn’t doing any tricks in my CursorAdapter, just setting the raw data to the TextView. There was something out of the ordinary for my case, in that some of my TextViews were using arabic characters, some were using western characters while others were mixing arabic and western.
Hierarchy Viewer to the Rescue
In typical Android fashion, I then turned to the tool we all use when something is amiss with our layouts. Hierarchy Viewer! One of many tucked away tools in the SDK. Frustratingly, if an Arabic TextView was present in my layout, Hierarchy Viewer would not run! This led me to file a bug against the hierarchy viewer.
Ok, no problem, I’ll just inspect a blanked out view that doesn’t have any arabic in it. Now when I run hierarchy viewer, the act of running hierarchy viewer fixes my view?!?
Pop quiz, what are 2 things that hierarchy viewer does to every element in your layout?
- Calls invalidate
- Calls requestLayout
A simple change to my CursorAdapter to requestLayout after setting the text solved the problem.
Note to Arabic Developers
From the arabic proverb
A horse that will not carry a saddle must have no oats.
Or perhaps the more familiar version
ويجب على الحصان الذي لن يحمل سرج ليس لديهم الشوفان.
What does this have to do with Android? Absolutely nothing! But if you plan on using both of these in a ListView, prepare to requestLayout or there will be much tearing of clothes and gnashing of teeth.