Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove view on the child's parent? android

So I have a button that displays an alert dialog when its clicked. I create the view for the alert dialog in the onCreate method of my activity. The code for that is right here:

    LayoutInflater factory = LayoutInflater.from(this);
    view = factory.inflate(R.layout.grade_result, null);

When I push the button for the first time, the dialog displays the way I want it, but when I push it a second time it throws this exception.

11-28 00:35:58.066: E/AndroidRuntime(30348): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

My code for the method that displays the AlertDialog when the button is pushed is right here:

public void details(View v){
    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setView(view);
    alert.setMessage("Details About Your Grades")
    .setCancelable(false)
    .setPositiveButton("Continue", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id){
            dialog.cancel();

        }
    });
    alert.show();

Any help would be appreciated! Thank you!

like image 639
vinee109 Avatar asked Nov 28 '12 08:11

vinee109


1 Answers

Inflating the view that should be set within the Builder of the AlertDialog worked for me :

Button mButton = (Button) findViewById(R.id.my_button);
mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // inflating view out of the onClick() method does not work
            LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final ViewGroup viewGroup= (ViewGroup) mInflater.inflate(R.layout.my_view, null);

            Dialog alertDialog = new AlertDialog.Builder(getActivity())
                    .setTitle(R.string.my_title)
                    .setView(viewGroup)
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).create();
            alertDialog.show();
        }
}
like image 85
Vince Avatar answered Sep 23 '22 10:09

Vince