动态地向线性布局添加内容? [英] Adding content to a linear layout dynamically?

查看:30
本文介绍了动态地向线性布局添加内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If for example I have defined a root linear layout whose orientation is vertical:

ma​​in.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>

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

Inside the root linear layout, I would like to add multiple child linear layouts, each of the child linear layout orientation is horizontal. With all these I could end up with a table like output.

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

For example root with child layout such as:

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

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

Since the number of child linear layouts and their contents are quite dynamic, I've decide to add content to the root linear layout programmatically.

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

How can the second layout be added to the first programmatically, which could also set all the layout attributes for each child and add more other elements inside child?

推荐答案

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

In your onCreate(), write the following

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.它们很容易以编程方式创建.

view1, view2 and view3 are your TextViews. They're easily created programmatically.

这篇关于动态地向线性布局添加内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆