[英]How can dynamically add a View to a ViewGroup and vertically align with one of its child
I have a ViewGroup and it has a few children.我有一个 ViewGroup,它有几个孩子。 And one of them is a TextView ("+id/text").
其中之一是 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")?
在我的代码中,我想知道如何添加一个新的 View 或 ViewGroup,它们将垂直对齐并位于 TextView 下方(+“id/text”)?
I have followed the advice below and try to use TableLayout.我已遵循以下建议并尝试使用 TableLayout。 As a test, I try to layout statically to make sure things are aligned correctly.
作为测试,我尝试静态布局以确保正确对齐。
Here is my layout xml:这是我的布局 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>
But when i run in on emulator.但是当我在模拟器上运行时。 The ImageButton on the 2nd row, does not align vertically with the textView in 1st row.
第二行的 ImageButton 与第一行的 textView 不垂直对齐。 Any idea why?
知道为什么吗?
Consider using a TableLayout as your ViewGroup.考虑使用 TableLayout 作为您的 ViewGroup。 With a TableLayout you can programmatically add a child at a specific location.
使用 TableLayout,您可以以编程方式在特定位置添加子项。
View view = new ViewIWantToAdd();
TableLayout layout = (TableLayout)findViewById(R.id.table_layout);
layout.addView(view);
Would add a view at the bottom of the TableLayout.将在 TableLayout 的底部添加一个视图。 Typically you would use a TableRow as the contents of the TableView, but you can add any view.
通常,您将使用 TableRow 作为 TableView 的内容,但您可以添加任何视图。
If your layout is not so complex, use RelativeLayout如果您的布局不是那么复杂,请使用RelativeLayout
A Layout where the positions of the children can be described in relation to each other or to the parent...
可以相对于彼此或父级描述子级位置的布局...
When you insert a new child view, create a new LayoutParams then setRule当你插入一个新的子视图时,创建一个新的 LayoutParams 然后setRule
You can put the child view below the textView with this你可以把TextView的下方的子视图与此
:) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.