3

I have build a layout programmatically in Android (a treeview) and now I'd like to add to the built view a topbar (topbar.xml).

So what I need is instead of:

setContentView(scroll)

Something like:

inflateInMyViewCalledScroll(topbar.xml)
setContentView(scroll)

Thanks for your suggestions

Luigi Tiburzi
  • 4,265
  • 7
  • 32
  • 43

2 Answers2

6

Inflate topbar.xml using LayoutInflater, putting the results into scroll:

getLayoutInflater().inflate(R.layout.topbar, scroll);
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I already tried this but I get RuntimeException "unable to start Activity ..." – Luigi Tiburzi Apr 08 '13 at 14:15
  • @LuigiTiburzi: When you examined the Java stack trace in LogCat associated with this exception, what did you learn? – CommonsWare Apr 08 '13 at 14:17
  • It says scrollView can host only one direct child... but I need it to have a topbar... – Luigi Tiburzi Apr 08 '13 at 14:21
  • 1
    @LuigiTiburzi: "It says scrollView can host only one direct child" -- correct. "but I need it to have a topbar" -- then you need the "topbar" and other stuff to be in some other container. See Matt's answer. – CommonsWare Apr 08 '13 at 14:25
5

ScrollView can only have one direct child.

So you have to do something like this:

<ScrollView>
    <LinearLayout android:id="@+id/foo" android:orientation="vertical">
        <!--  youll add topbar here, programmatically -->
        <other things/>
    </LinearLayout/>
</ScrollView>

And then at runtime, you'll inflate topbar

View topbar = getLayoutInflater().inflate(R.layout.topbar, null);

and add it as the first index in foo

foo.addView(topbar, 0);
Matt
  • 5,461
  • 7
  • 36
  • 43
  • I'm sorry to bother but your trick is causing me some problem. For example I can't find the resources I'm looking for (it's like the com.controller.R class haven't the specified resources). Moreover I don't want the topbar to be scrolled, I add a resource to the scroll that I want scrolled and I'd like to have the topbar fix at the top... – Luigi Tiburzi Apr 09 '13 at 07:09
  • Ok I had a problem that I was able to fetch the layout but then I couldn't add to it other components. I created a new LinearLayout and added all to it. Thanks!! – Luigi Tiburzi Apr 09 '13 at 08:16