You must call removeView() on the child's parent first

在做alertdialog是的时候报了这么一个错误:

java.lang.IllegalStateException:
The specified child already has a parent.
You must call removeView() on the child's parent first.

搞了许久,终于理解了。

et1 = (EditText)findViewById(R.id.editText1);
builder.setView(et1); -- AlertDialog.Builder builder

et1我写在了xml里面,这样报错,原因是一女不可二嫁。

et1的parent即是R.layout.main 又是AlertDialog。

自然就报错了要你removeView()了。

解决方法有两种

1.动态生成EditText

et1 = new EditText(this);
builder.setView(et1);

2. 放在另一个xml中,用inflater

LayoutInflater inflater = LayoutInflater.from(this);  
View textEntryView = inflater.inflate(R.layout.test1, null);
et1 = (EditText)textEntryView.findViewById(R.id.editText1);
builder.setView(textEntryView ); 注意这里是textEntryView ,不是et1 




原文地址:https://www.cnblogs.com/shenbin/p/2398209.html