图片来源于网络
EditText edit_uuid = new EditText(Activity.this);
//点击按钮弹出一个可以编辑的对话框
btn_addUuid.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new AlertDialog.Builder(UuidActivity.this).setTitle("请输入").setIcon(
android.R.drawable.ic_dialog_info).setView(
edit_uuid).setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String uuid=edit_uuid.getText().toString();
Db.insert(uuid);
dialogInterface.dismiss();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).create().show();
}
});
}
到此我们的弹出框就完成了,但是当我们再次点击按钮是会出现错误
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
出现此原因是edit_uuid 实例化后被保存,所以当第二次重新创建父类的时候,父类已经是新的,而子类还是原来的,所以在重新点击的时候,要进行判断,移除布局
public void onClick(View view) {
***if(edit_uuid.getParent()!=null){
((ViewGroup) edit_uuid.getParent()).removeView(edit_uuid);
}***
new AlertDialog.Builder(UuidActivity.this).setTitle("请输入").setIcon(
android.R.drawable.ic_dialog_info).setView(
edit_uuid).setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String uuid=edit_uuid.getText().toString();
Db.insert(uuid);
getData();
uuidAdapter.notifyDataSetChanged();
dialogInterface.dismiss();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i)
dialogInterface.dismiss();
}
}).create().show();
}
});