【问题标题】:Adding multiple child views to parent view将多个子视图添加到父视图
【发布时间】:2012-06-07 14:01:28
【问题描述】:

我在ScrollView (ma​​in.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


    【解决方案1】:

    在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"); 
    

    【讨论】:

    • 但是你在 txt1.setText("PLANE");设置在 txt2.setText("PLANE");
    【解决方案2】:

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

    findViewById(R.id.root);
    

    【讨论】:

    • 我不懂你,我用的是“(LinearLayout) contentView.findViewById(R.id.root);” ,这是怎么回事???
    • 您是否在活动中的某处使用 setContentView(int) 来设置布局?也许我假设您这样做是错误的,但如果是这种情况,那么这就是您错误的根源。那你会用吗?
    • Perhaos 你可以把整个类都转储到 pastebin 什么的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多