Reputation: 523
I'm currently creating an application that adds rows to an existing table. The code looks like this:
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);
In the XML I've got a table layout that's inside a linearLayout thats inside a frameLayout thats inside a tabwidget and it looks like this:
<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>
Creating those labels works fine, but when I want to add the text to a row, the application crashes and I get an "IllegalStateException", the detailed message is:
The specified child already has a parent. You must call removeView() on the child's parent first.
I don't quite get it. When I look at a tutorial like this there isn't anything that has to be removed first. So what exactly am I doing wrong?
Upvotes: 2
Views: 747
Reputation: 43108
Your textview is already a child of another view. You cannot simply change the parent - you must remove the view from one parent and add it to another.
Looking closer, you simply don't have to manually add the particular text view to the table row - it is already there according to your xml.
addView() method usually invoked for newly created views, not for the ones you define in xml.
Upvotes: 2
Reputation:
The exampleLabel that you add in your code to the tableRow you added already in the XML file to the same table.
Since a UI element can only have one parent, this isn't possible.
I also don't know why you want to add it again, since it is already added to the exactly same view.
In your tutorial I can0t find a textview that is already added to the table in the xml file?
Upvotes: 1