在xml中root的Android父级?

时间:2014-09-20 15:59:15

标签: android

如果我有两个布局,layout1.xml和layout2.xml,它们都是空的LinearLayouts,我将layout1设置为活动的内容视图:

setContentView(R.layout.layout1);

是否可以在第一个布局下添加第二个布局?

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout2 = (LinearLayout) inflater.inflate(R.layout.layout2);
View parent = // parent of current layout root
parent.addView(layout2);

所以层次结构看起来像:

<parent>
    <layout1 />
    <layout2 />
</parent>

基本上我想知道如何获得父视图。

3 个答案:

答案 0 :(得分:1)

我认为最简单的方法是创建第三个布局(parent.xml),其中包含使用include标签的其他两个布局。然后是setContentView(R.layout.parent);

看看这里:

http://developer.android.com/training/improving-layouts/reusing-layouts.html

作为示例,请考虑以下父布局,其中包含其他两种布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include android:id="@+id/layoutOne" layout="@layout/layout1" android:layout_width="match_parent" android:layout_height="wrap_content"/>
    <include android:id="@+id/layoutTwo" layout="@layout/layout2" android:layout_width="match_parent" android:layout_height="wrap_content"/>

</LinearLayout>

答案 1 :(得分:0)

   View parent= getWindow().getDecorView().findViewById(android.R.id.content)

答案 2 :(得分:0)

我想你想要这样的东西:

LinearLayout layoutMain = new LinearLayout(this);
    layoutMain.setOrientation(LinearLayout.VERTICAL);
    setContentView(layoutMain);
    LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    RelativeLayout layoutFirst = (RelativeLayout) inflate.inflate(R.layout.abc, null);
    RelativeLayout layoutSecond = (RelativeLayout) inflate.inflate(R.layout.xyz, null);
    layoutMain.addView(layoutFirst, 100, 100); // width=100, height=100
    layoutMain.addView(layoutSecond, 100, 100);

您可以阅读文档here