Em getting java.lang.IllegalStateException:指定的子节点已经有父节点。您必须首先在孩子的父母身上调用removeView()。
无法找出必须删除的视图,任何帮助都会非常有用。
以下是代码段
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:id="@+id/mainLayout"
android:layout_height="fill_parent"
android:orientation="vertical" >
</RelativeLayout>
data.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</RelativeLayout>
活动代码
public class ToDo extends Activity {
/** Called when the activity is first created. */
Button addNew;
RelativeLayout mainLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainLayout=(RelativeLayout)findViewById(R.id.mainLayout);
RelativeLayout rel;
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for(int idx=0;idx<2;idx++){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rel = (RelativeLayout) inflater.inflate(R.layout.data,null);
params.setMargins(0, 50, 0, 0);
TextView fromWeb= (TextView) rel.findViewById(R.id.txt);
fromWeb.setText("AA");
mainLayout.addView(rel,params);
}
}
}
答案 0 :(得分:0)
以下代码不正确:
TextView fromWeb= (TextView) rel.findViewById(R.id.txt);
fromWeb.setText("AA");
rel.addView(fromWeb,params); // the TextView is alredy in the rel RelativeLayout!
mainLayout.addView(rel);
因为您正在添加 (使用addView
方法)TextView
已放置在布局文件中(因为您之前使用{{1}搜索了它})。相反它应该是这样的:
findViewById
如果您想要TextView fromWeb= (TextView) rel.findViewById(R.id.txt);
fromWeb.setText("AA");
mainLayout.addView(rel);
的边距,请在布局文件中设置它们:
TextView