例如,如果我定义了一个方向为垂直的根线性布局:
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>
由于子线性布局的数量及其内容是非常动态的,因此我决定以编程方式将内容添加到根线性布局中。
如何以编程方式将第二个布局添加到第一个布局中,这也可以为每个子级设置所有布局属性,并在子级中添加更多其他元素?
发布于 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);
view1
、view2
和view3
是你的TextView
,它们很容易通过编程创建。
发布于 2011-07-12 16:25:24
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
View child = getLayoutInflater().inflate(R.layout.child, null);
layout.addView(child);
发布于 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);
https://stackoverflow.com/questions/6661261
复制相似问题