我試圖將新的TableRows
添加到TableLayout
,但我甚至無法將TextView
添加到新的TableRow
對象。但總是有相同的錯誤:無法將TextView添加到新的TableRow中(指定的子項已有父項)
04-25 12:11:42.329: E/AndroidRuntime(26636): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
這是主代碼:
public static class PlaceholderFragment extends Fragment {
protected TableLayout mTableLayout;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_results,
container, false);
mTableLayout = (TableLayout) rootView
.findViewById(R.id.results_table);
fullFillTable();
return rootView;
}
private void fullFillTable() {
TextView labelPosition = new TextView(getActivity());
TableRow row = new TableRow(getActivity());
labelPosition.setText("Pos");
row.addView(labelPosition); //The error is here
mTableLayout.addView(row);
}
}
這裏是fragment.xml
:
<TableLayout
android:id="@+id/results_table"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/activity_vertical_margin"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:layout_marginRight="@dimen/activity_horizontal_margin"
android:layout_marginTop="@dimen/activity_vertical_margin"
android:stretchColumns="*" >
<TableRow
android:id="@+id/results_titles_row"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F7F7F7" >
<TextView
android:id="@+id/results_col1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/results_col1_title" />
<TextView
android:id="@+id/results_col2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/results_col2_title" />
<TextView
android:id="@+id/results_col3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/results_col3_title" />
<TextView
android:id="@+id/results_col4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/results_col4_title" />
</TableRow>
</TableLayout>
有誰知道如何解決這個問題?
感謝
謝謝,我改變了這一點。但問題出在第一個addView() –
@marc_aragones,你確定嗎?您是否使用固定代碼重建項目? –
是的,當然。 logcat說錯誤在這行:row.addView(labelPosition); –