【发布时间】:2012-06-07 14:01:28
【问题描述】:
我在ScrollView (main.xml) 中有一个LinearLayout 视图元素:
<ScrollView ...>
<LinearLayout
android:id="@+id/root"
android:orientation="vertical"
>
<TextView .../>
<EditText .../>
...
</LinearLayout>
</ScrollView>
正如您在上面看到的,root LinearLayout 中还有一些其他元素。
现在,我想以编程方式(动态)向LinearLayout (id="root") 添加更多视图。
我尝试了以下方式向这个root添加更多子视图:
首先,我在单独的布局文件中创建了我的子视图:
child.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 布局,而在“root”下看不到 child_1,为什么??
【问题讨论】:
标签: android android-layout android-intent android-emulator android-widget