将ViewGroup添加到ViewGroup

时间:2011-12-08 17:48:10

标签: android viewgroup

我希望能够以编程方式将视图组添加到另一个视图组。两者都在xml中定义如下,以及我的onCreate方法:

main.xml中:

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

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="first text" />

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="second text" />

secondlayout.xml:

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

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="first text" />

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="second text" />

的onCreate:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Context context = getBaseContext();

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.main, null);
    LinearLayout tv = (LinearLayout) inflater.inflate(R.layout.secondlayout, null);
    tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    ll.addView(tv);
    setContentView(ll);
}

1 个答案:

答案 0 :(得分:1)

findViewById(R.layout.secondlayout)执行内容时,您尝试在设置内容视图之前查找视图。此外,secondlayout不是视图的ID,它是布局文件的名称和ID。

尝试

LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.main, null);
LinearLayout tv = (LinearLayout) inflater.inflate(R.layout.secondlayout, null);
tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
ll.addView(tv);
setContentView(ll);
相关问题