我在(main.xmlLinearLayout
)中有一个视图元素:ScrollView
<ScrollView ...>
<LinearLayout
android:id="@+id/root"
android:orientation="vertical"
>
<TextView .../>
<EditText .../>
...
</LinearLayout>
</ScrollView>
正如您在上面看到的,在root 中还有一些其他元素LinearLayout
。
现在,我想以编程方式(动态地)向LinearLayout
(id="root") 添加更多视图。
我尝试了以下方法向该根添加更多子视图:
首先,我创建了位于单独布局文件中的子视图:
子.xml
<LinearLayout
android:id="@+id/child"
>
<TextView id="mytxt"... />
<ListView id="mylist".../>
</LinearLayout>
其次,我膨胀并获取上述子视图的两个实例,初始化里面的元素:
/***inflate 1st child, initialize its elements***/
LinearLayout child_1 = (LinearLayout) inflater.inflate(R.layout.child, null);
TextView txt1 = (TextView)child_1.findViewById(R.id.mytxt);
txt1.setText("CAR");
ListView list1 = (ListView)child_1.findViewById(R.id.mylist);
// Code to initialize 'list1' (I did not paste code here)
/*** inflate 2nd child, initialize its elements ****/
LinearLayout child_2 = (LinearLayout) inflater.inflate(R.layout.child, null);
TextView txt2 = (TextView)child_2.findViewById(R.id.mytxt);
txt2.setText("PLANE");
ListView list2 = (ListView)child_2.findViewById(R.id.mylist);
// Code to initialize 'list2' (I did not paste code here)
最后,我将它们添加到root LinearLayout
:
//get root
View contentView = inflater.inflate(R.layout.main, null);
LinearLayout root = (LinearLayout) contentView.findViewById(R.id.root);
//add child views
root.add(child_1);
root.add(child_2);
当我在设备上运行我的应用程序时,我只能看到child_2
布局而看child_1
不到“root”,为什么?