Inflate a view / layout into another layout?

后端 未结 2 639
孤独总比滥情好
孤独总比滥情好 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: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);
    

提交回复
热议问题