我在动态添加TextView时遇到问题。我想首先通过方法getRoomList()
从列表中添加租用的房间,然后添加带有文本":Free"的房间,这些房间位于existingRoomNames
数组中但未被雇用。
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);
那里的问题是什么?
答案 0 :(得分:2)
您正在再次向布局添加相同的视图。 将您的功能更改为
public void addNotHiredRoomsToLayout() {
for (String name : Constants.existingRoomNames) {
textView2 = new TextView(this);
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);
}
}
}
答案 1 :(得分:1)
移动
J/N
里面
linearLayout = (LinearLayout) findViewById(R.id.linear1);
linearLayout.removeAllViews();
答案 2 :(得分:1)
问题是您每次都使用相同的TextView。 如果要使用多个TextView,请将循环更改为
for (String name : Constants.existingRoomNames) {
textView2 = new TextView(this); //create a new TextView that wasn't added to layout yet
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);
}
}
答案 3 :(得分:0)
请试试这个 - &gt;制作一个名为“text_view”的xml布局文件:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
然后排队解决这个问题:
textView2 = (TextView) getLayoutInflater().inflate(R.layout.text_view, null);