首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >动态地将内容添加到线性布局?

动态地将内容添加到线性布局?
EN

Stack Overflow用户
提问于 2011-07-12 16:15:09
回答 4查看 133.4K关注 0票数 80

例如,如果我定义了一个方向为垂直的根线性布局:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/my_root"
      android:layout_height="wrap_content"
      android:layout_width="fill_parent"
      android:orientation="vertical"

    <!-- I would like to add content here dynamically.-->

</LinearLayout>

在根线性布局中,我想添加多个子线性布局,每个子线性布局的方向都是水平的。有了所有这些,我可以得到一个类似于输出的表。

例如,具有子布局的root,如:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/my_root"
      android:layout_height="wrap_content"
      android:layout_width="fill_parent"
      android:orientation="vertical"

    <!-- 1st child (1st row)-->
    <LinearLayout 
        ...
       android:orientation="horizontal">

          <TextView .../>
          <TextView .../>
          <TextView .../>
    </LinearLayout>

     <!-- 2nd child (2nd row)-->
     ...
</LinearLayout>

由于子线性布局的数量及其内容是非常动态的,因此我决定以编程方式将内容添加到根线性布局中。

如何以编程方式将第二个布局添加到第一个布局中,这也可以为每个子级设置所有布局属性,并在子级中添加更多其他元素?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-07-12 16:26:01

在您的onCreate()中,编写以下内容

LinearLayout myRoot = (LinearLayout) findViewById(R.id.my_root);
LinearLayout a = new LinearLayout(this);
a.setOrientation(LinearLayout.HORIZONTAL);
a.addView(view1);
a.addView(view2);
a.addView(view3);
myRoot.addView(a);

view1view2view3是你的TextView,它们很容易通过编程创建。

票数 107
EN

Stack Overflow用户

发布于 2011-07-12 16:25:24

LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
View child = getLayoutInflater().inflate(R.layout.child, null);
layout.addView(child);
票数 78
EN

Stack Overflow用户

发布于 2011-07-12 16:27:10

您可以像这样实现LinearLayout级联:

LinearLayout root = (LinearLayout) findViewById(R.id.my_root);    
LinearLayout llay1 = new LinearLayout(this);    
root.addView(llay1);
LinearLayout llay2 = new LinearLayout(this);    
llay1.addView(llay2);
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6661261

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档