我希望能够以编程方式将视图组添加到另一个视图组。两者都在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);
}
答案 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);