我在動態添加TextViews時遇到了問題。我想首先通過方法getRoomList()
從列表中添加租用的房間,然後添加帶有文本「:Free」的房間,這些房間位於existingRoomNames
陣列中,但未被僱傭。將多個TextViews動態添加到LinearLayout中
public void checkRoomsAndDate() {
linearLayout = (LinearLayout) findViewById(R.id.linear1);
linearLayout.removeAllViews();
for (Room room : mCalendarModel.mList.getRoomList()) {
addHiredRoomToLayout(room);
}
addNotHiredRoomsToLayout();
}
public void addHiredRoomToLayout(Room room) {
textView = new TextView(this);
textView.setText(room.getParameters());
linearLayout.addView(textView);
}
public void addNotHiredRoomsToLayout() {
textView2 = new TextView(this);
for (String name : Constants.existingRoomNames) {
boolean contains = false;
for (Room room : mCalendarModel.mList.getRoomList()) {
if (room.getName().equals(name)) {
contains = true;
}
}
if (!contains) {
textView2.setText(name + ": Free");
linearLayout.addView(textView2);
}
}
}
這裏的XML:
<LinearLayout
android:orientation="vertical"
android:layout_width="313dp"
android:layout_height="150dp"
android:id="@+id/linear1"
android:layout_gravity="center"></LinearLayout>
這是父的LinearLayout內。
我得到的例外是這樣的:
`java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.`
在最後一行:
linearLayout.addView(textView2);
什麼問題呢?
如果解決了您的問題,請將答案標記爲已接受。 –
解決了,謝謝你! –