将多个子视图添加到父视图

时间:2012-06-07 14:01:28

标签: android android-layout android-intent android-emulator android-widget

我在LinearLayout main.xml )中有一个ScrollView视图元素:

<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>

其次,我膨胀&amp;获取上面子视图的两个实例,初始化里面的元素:

/***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,为什么?

2 个答案:

答案 0 :(得分:2)

在LinearLayout默认方向是水平设置它垂直.......

http://developer.android.com/reference/android/widget/LinearLayout.html

默认方向是水平的。

and you set text in txt1.setText("PLANE"); set in  txt2.setText("PLANE");

both text set in same textview .....

    txt1.setText("CAR");
    txt1.setText("PLANE"); 

答案 1 :(得分:1)

如何创建布局?你是通过setContentView(int)做到的吗?然后,您应该在活动中执行此操作来检索该实例:

findViewById(R.id.root);