I want to create a XML layout dynamically but I had a question on doing so.
Say I have something like this (Looking at the layout from the “Outline” perspective):
-ScrollView
—Linear Layout(Vertical) (LL1)
——-Linear Layout(Horizontal) (LL2)
———–Image View (IV1)
———–Linear Layout(Vertical) (LL3)
—————TextView
—————TextView
So my question here is would I start with the most inner Layout (LL3) and add the 2 TextViews and then branch upwards (to LL2 then LL1 then ScrollView) with adding to the other views & layouts?
I believe you can do this several ways. I’ve not tried creating an entire hierarchy like this dynamically, but I’ve added buttons, radio-buttons, text-views and other Views this way several times. In those cases, I’ve just added new ones to the ones that already exist using
AddView().I think the easiest way is to just create it “top down”, i.e. create the
ScrollViewfirst and add any settings, then add the other views to it downwards. I would typically do something like this:Now populate them in the right way:
Note:
I do believe this should work, but I can not guarantee it; if the reference to an inner view is no longer correct after having been added to an outer view (Eg.
myHorizontalLayoutis no longer a valid ref to the actual view undermyScrollView), you might not be able to add children to that inner view. Not sure about this, though.(If so, you might try to fetch a new, correct reference using
findViewByName()after adding each view, but I don’t think that would be an optimal solution).I would try the first way first – at least make a proof of concept, to see that you can add view in a hierarchy at least three levels deep. That should give you your answer. If it does not work, I suppose I would try adding them in the opposite order, as you suggest in your question, just to see if that works (maybe just switch the order in my second code block?).
Sorry for the imprecise answer, hope it is of some help anyway.