124697
124697

Reputation: 21901

"The specified child already has a parent" How can I remove view from AlertDialog

I am inflating a LinearLayout into an AlertDialog. it works fine but if I dismis it and launch it again it gives me the following error

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

in the contructor:

infoWindow = (LinearLayout) ((Activity) context).getLayoutInflater().inflate(R.layout.map_info_content, null);

later:

protected boolean onTap(int index) {
        Builder dialog = new AlertDialog.Builder(context);
        dialog.setView(infoWindow);
        dialog.show();
        return true;
    }

I have tried to keep the dialog in memory and setting it's view as null but it didn't fix the problem

Upvotes: 0

Views: 697

Answers (1)

Saket
Saket

Reputation: 3086

You cannot re-use inflated views in Android once you've added them to a parent ViewGroup. At your side, you're trying to reuse an inflated view in your dialog. To solve this problem, inflate the view in your AlertDialog class itself.

I'd recommend you to create a separate class for it. Here's how the onCreateDialog method would look like:

public Dialog onCreateDialog(Bundle savedInstance){

    // create a new dialog builder
    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

    // dialog view to inflate
    View view = getActivity().getLayoutInflater()
                                .inflate(R.layout.map_info_content, null);

    // sets the view of our dialog
    builder.setView(view);

    // create and return the dialog
    return builder.create();
}

Upvotes: 3

Related Questions