Inflate a view / layout into another layout?

后端 未结 2 618
孤独总比滥情好
孤独总比滥情好 2020-11-28 15:15

I\'m looking for a way to inflate another layout into the first layout in android. How would one do this? Here are the two XML files. The first is the main layout, the secon

相关标签:
2条回答
  • 2020-11-28 15:34

    I'm not sure I realy understood what had you ment by "I can't just include the layout as I will use this method to inflate other layouts into wire frames later on." But if you need the second layout to be put many times in various other layouts, use <include layout="@layout/the_second_layout" /> in these other layouts.

    0 讨论(0)
  • 2020-11-28 15:38

    There is ViewStub but I never used it and I think it can't be used more than once.

    You can inflate the menu layout and attach it to the main layout:

    AbsoluteLayout mainLayout = (AbsoluteLayout) findViewById(R.id.your_main_layout);
    LayoutInflater inflater = 
                  (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View menuLayout = inflater.inflate(R.layout.your_menu_layout, mainLayout, true);
    

    then when you want to change you can remove it:

    mainLayout.removeView(menuLayout);
    

    and add another the same way.

    This will work because you want to add the layout as the last child of the parent layout. If you want to add it, say, at 1st position, you can inflate your layout without attaching it to the parent (use false as last arg), and adding it manually specifying the index:

    mainLayout.addView(menuLayout, 0);
    
    0 讨论(0)
提交回复
热议问题