2

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

主.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" />

创建:

@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);
}
4

1 回答 1

2

您尝试在设置内容视图之前查找视图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);
于 2011-12-08T18:01:59.623 回答