android - 在 Android 上向 TableRow 添加 View 时出现 IllegalStateException

标签 android android-tablelayout illegalstateexception

我当前正在创建一个向现有表添加行的应用程序。代码如下所示:

TextView exampleTextView = (TextView) messageView.findViewById(R.id.exampleLabel);
exampleTextView.setText(locationMsg.getMessageContent());

TableRow tr = (TableRow) messageView.findViewById(R.id.tableRow);
tr.addView(exampleTextView);
table.addView(tr);

在 XML 中,我有一个表格布局,它位于 LinearLayout 内,而 LinearLayout 位于 TabWidget 内的 FrameLayout 内,它看起来像这样:

<TableLayout
 android:id="@+id/distanceTable" 
 android:layout_height="wrap_content"
 android:layout_width="wrap_content"
 android:layout_gravity="center"
 android:background="#DDDDDD"
 android:stretchColumns="1" >
 <TableRow>
  <TextView
  android:textColor="#000000"
  android:text="@string/label_device"
  android:layout_gravity="center"
  android:padding="3dip"
  android:textSize="18sp" />

  <TextView
  android:textColor="#000000"
  android:text="@string/label_distance"
  android:layout_gravity="center"
  android:padding="3dip"
  android:textSize="18sp" />
  <TextView
  android:textColor="#000000"
  android:text="@string/label_time"
  android:layout_gravity="center"
  android:padding="3dip"
  android:textSize="18sp" />
 </TableRow>
 <TableRow android:id="@+id/tableRow" >
  <TextView
  android:id="@+id/exampleLabel"
  android:textColor="#000000"
  android:layout_gravity="center"
  android:padding="3dip"
  android:textSize="18sp" />
  <TextView
  android:id="@+id/anotherExampleLabel"
  android:textColor="#000000"
  android:layout_gravity="center"
  android:padding="3dip"
  android:textSize="18sp" />
  <TextView
  android:id="@+id/someOtherLabel"
  android:textColor="#000000"
  android:layout_gravity="center"
  android:padding="3dip"
  android:textSize="18sp" />
 </TableRow>
</TableLayout>

创建这些标签工作正常,但是当我想将文本添加到一行时,应用程序崩溃并且我收到“IllegalStateException”,详细消息是:

The specified child already has a parent. You must call removeView() on the child's parent first.

我不太明白。当我查看像 this 这样的教程时没有任何东西需要先删除。 那么我究竟做错了什么?

最佳答案

您的 TextView 已经是另一个 View 的 subview 。您不能简单地更改父级 - 您必须从一个父级中删除 View 并将其添加到另一个父级中。

仔细观察,您根本不必手动将特定的 TextView 添加到表行 - 根据您的 xml,它已经存在了。

addView() 方法通常为新创建的 View 调用,而不是为您在 xml 中定义的 View 调用。

关于android - 在 Android 上向 TableRow 添加 View 时出现 IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4850873/

相关文章:

java - 如何在 Android 中更改 TableRow 的高度?

Android DownloadManager illegalstateexception 无法创建目录

javascript - 如何从 Android 移动设备键盘获取键码?

android - 从 AppGallery Connect API 获取错误代码 204144647,消息为 "The new service has can' 无法编辑服务,无法更新

android - 在 Android 中创建 UI 表的最佳方式

android - 如何在表布局中动态添加行或如何在单表布局中显示完整的数据库记录

android - 在操作栏android上添加搜索图标

java - 机器人 : how to create new Directory in my package path

java.awt.IllegalComponentStateException

java - 还有一个 mediaPlayer IllegalStateException : screen timeout