Android AlertDialog嵌套及二调用报错解决方法:The specified child already has a parent. You must call removeView()

在AlertDialog中重新调用一个AlertDialog时会出现错误:

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

出错的代码为:

final LayoutInflater factory2 = LayoutInflater.from(this);
final View textEntryView2 = factory2.inflate(R.layout.findroom,
null);


final AutoCompleteTextView building = (AutoCompleteTextView) textEntryView2
.findViewById(R.id.autoCompleteTextRoom);


// 声明适配器
ArrayAdapter adapter2 = new ArrayAdapter(this,
android.R.layout.simple_dropdown_item_1line, buildingNames);


building.setAdapter(adapter2);


// 下拉列表
final Spinner sp1 = (Spinner) textEntryView2
.findViewById(R.id.spinnerTime);
ArrayAdapter Ad = ArrayAdapter.createFromResource(
this, R.array.timelist,
android.R.layout.simple_spinner_item);
Ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(Ad);


AlertDialog.Builder dia = new AlertDialog.Builder(
UCMapActivity.this);


dia.setTitle("查询空教室:");
dia.setView(textEntryView2);
dia.setPositiveButton("确定", new OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
String name = building.getText().toString().trim();
if (name.equals("")) {
toast("输入不能为空!");
} else {

FindRoomDao mts = new FindRoomDao(sqlite);


final View showRoomMessage = factory2.inflate(
R.layout.showroommessage, null);


final TextView showRoomText = (TextView) showRoomMessage
.findViewById(R.id.showRoomMessage);



showRoomText.setText("");
showRoomText.setText(mts.run(name, sp1
.getSelectedItem().toString()));

// new PopupWindow(showRoomMessage).showAtLocation(showRoomMessage, Gravity.BOTTOM, Gravity.LEFT, Gravity.RIGHT);
AlertDialog.Builder showRoomDia = new AlertDialog.Builder(
UCMapActivity.this) {
public AlertDialog show() {
//再次绑定View  
   setView(showRoomMessage);  
   return super.show(); 
}
};


showRoomDia.setTitle("查询空教室结果:");
showRoomDia.setView(showRoomText);


showRoomDia.setNegativeButton("确定",
new OnClickListener() {


@Override
public void onClick(DialogInterface arg0,
int arg1) {
arg0.dismiss();
}


});


showRoomDia.show();
}


}
});
dia.setNegativeButton("取消", new OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});


dia.show();


 而提示的大致意思是说为一个子视图指定了多个父视图。由此可以推断出,在第二次点击按钮弹出对话框时,子视图与第一次点击时的子视图是同一个对象,而父视图已经不再是同一个对象了。解决方法非常简单,只需要重写对话框的show()方法即可:

@Override

//重写show()方法

 public AlertDialog show() 

 //再次绑定

View setView(GetTextEntryView()); 

 return super.show();

 }

你可能感兴趣的:(Android AlertDialog嵌套及二调用报错解决方法:The specified child already has a parent. You must call removeView())