2

我在(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”,为什么?

4

2 回答 2

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"); 
于 2012-06-07T14:03:08.417 回答
1

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

findViewById(R.id.root);
于 2012-06-07T14:05:25.307 回答