如何动态地将视图添加到ViewGroup并与其子视图之一垂直对齐 [英] How can dynamically add a View to a ViewGroup and vertically align with one of its child
问题描述
我有一个ViewGroup,它有几个孩子.其中之一是TextView("+ id/text").在我的代码中,我想知道如何添加一个新的View或ViewGroup,它们将垂直对齐并位于TextView(+"id/text")下方?
I have a ViewGroup and it has a few children. And one of them is a TextView ("+id/text"). In my code, I would like to know how can I add a new View or ViewGroup which will be positioned vertically aligned and below the TextView (+"id/text")?
我遵循了以下建议,并尝试使用TableLayout.作为测试,我尝试静态布局以确保事物正确对齐.
I have followed the advice below and try to use TableLayout. As a test, I try to layout statically to make sure things are aligned correctly.
这是我的布局xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout android:id="@+id/panel" xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight">
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageButton
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:src="@drawable/icon"
android:layout_column="0" />
<LinearLayout
android:orientation="vertical"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_column="1">
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left" />
</LinearLayout>
</TableRow>
<TableRow>
<ImageButton
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="@drawable/icon"
android:layout_column="1"/>
</TableRow>
</TableLayout>
但是当我在模拟器上运行时.第二行的ImageButton与第一行的textView垂直不对齐.知道为什么吗?
But when i run in on emulator. The ImageButton on the 2nd row, does not align vertically with the textView in 1st row. Any idea why?
推荐答案
考虑将TableLayout用作ViewGroup.使用TableLayout,您可以通过编程方式在特定位置添加子项.
Consider using a TableLayout as your ViewGroup. With a TableLayout you can programmatically add a child at a specific location.
View view = new ViewIWantToAdd();
TableLayout layout = (TableLayout)findViewById(R.id.table_layout);
layout.addView(view);
将在TableLayout的底部添加一个视图.通常,您将使用TableRow作为TableView的内容,但是您可以添加任何视图.
Would add a view at the bottom of the TableLayout. Typically you would use a TableRow as the contents of the TableView, but you can add any view.
这篇关于如何动态地将视图添加到ViewGroup并与其子视图之一垂直对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!