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

Lee*_*eem 67 android android-layout

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

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>
Run Code Online (Sandbox Code Playgroud)

在根线性布局内,我想添加多个子线性布局,每个子线性布局方向都是水平的.有了这些,我最终会得到一个像输出这样的表格.

例如,具有布局的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>
Run Code Online (Sandbox Code Playgroud)

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

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

She*_*tib 96

在你的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);
Run Code Online (Sandbox Code Playgroud)

view1,view2并且view3是你TextView秒.它们很容易以编程方式创建.

  • 有人知道为什么吗?如果扩展了LinearLayout,为什么我不能只做this.addView(view1)? (2认同)

gre*_*561 69

LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
View child = getLayoutInflater().inflate(R.layout.child, null);
layout.addView(child);
Run Code Online (Sandbox Code Playgroud)

  • @Warapitiy使用`child.findViewById`来获取元素并设置onclick监听器. (2认同)

Bal*_*ake 5

您可以像这样实现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);
Run Code Online (Sandbox Code Playgroud)