android - 如何动态地将 View 添加到 ViewGroup 并与其子项之一垂直对齐

标签 android

我有一个 ViewGroup,它有几个 child 。其中之一是 TextView ("+id/text")。 在我的代码中,我想知道如何添加一个新的 View 或 ViewGroup,它们将垂直对齐并位于 TextView (+"id/text") 下方?

谢谢。

我已遵循以下建议并尝试使用 TableLayout。 作为测试,我尝试静态布局以确保正确对齐。

这是我的布局 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 垂直对齐。知道为什么吗?

最佳答案

考虑使用 TableLayout 作为您的 ViewGroup。使用 TableLayout,您可以以编程方式在特定位置添加子项。

View view = new ViewIWantToAdd();
TableLayout layout = (TableLayout)findViewById(R.id.table_layout);
layout.addView(view);

将在 TableLayout 的底部添加一个 View 。通常,您会使用 TableRow 作为 TableView 的内容,但您可以添加任何 View 。

关于android - 如何动态地将 View 添加到 ViewGroup 并与其子项之一垂直对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2241658/

相关文章:

java - 如何在低 API 级别获取 TimeZone?

android - 如何在您的应用程序中显示特殊字符?

android - MediaPlayer seekTo 不起作用

android - 在 Android 中发送和解析 JSON 对象

java - 广播经理不在 fragment 中工作

Android 应用程序不会在 Play 商店中更新

java - setPluginEnabled 未定义

javascript - 防止Android "long press"保存图片

Android ListView 不显示在 Bottom Sheet 中

java - 日期JSON解析形式