Today I have found an obscure problem that took me a few hours to figure it out and solve. I will write here how I have solved it, hope it can be of some help for some desperate developer.


We are developing an Android app that a given moment has this structure:

——–Sliding Tab Layout
————————Custom Views
——————————–Dynamically added views

Looks complicated, but is simple, think in a content fragment for a Navigation Drawer structure that contains a Sliding Tab Layout. The fragment inside one of the tabs of the Sliding Tab Layout contains a custom image gallery, created by extending a HorizontalScrollView. To that HorizontalScrollView we dynamically add ImageViews and TextViews to represent the images and their captions. Apart of the custom galery we are using other different customviews like a ViewPager and a TabView that follow a similar structure (in these cases the contents are directly defined in the XML layout)

The problem

When the fragment was loaded the first time, everything worked ok and was properly displayed, but when the main fragment was replaced and loaded again the views added dynamically inside the customviews didn’t appear.  The problem was somehow with the fragment internal loading, as the custom views worked ok when placed directly at the activity level.


After a few hours of trying different solutions that partially worked and involved nasty workarounds and hacks, the final (almost clean) solution was to delay the add of the custom views internal dynamic content using a Runnable

My guess is that the internal reference to the Layout generated during the initial fragment creation was somehow internally stored and not properly released during the fragment replace, and Android was trying to recreate it on the next attach before the view creation. The runnable makes the add to take place after the view creation and then the views are properly added to an existing parent view. Anyways as I said is a guess, but somehow related with the fragment problem.