Search code examples
androidcustomdialog

Get Reference of Dialog in onClick


I am creating a Custom Dialog on click of a button in my activity. There is button in the Dialog and I have set it like this:

 Button buttonTakePicture = (Button)dialog.findViewById(R.id.buttonTakePicture);
 buttonTakePicture.setOnClickListener(this);

My Activity is implementing the onClickListener, and the overridden onClick method looks like this:

@Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.buttonTakePicture:
                Dialog dialog = //Get the dialog somehow from view;
                if (dialog != null) {
                    dialog.dismiss();
                }
                takePicture();
                break;
        }
    }

I am struggling to get the Dialog Reference here. I have tried (Dialog)view.getParent() as well as (Dialog)view.getParent.getParent(), but they are not the Dialogs.

I don't want to have a Dialog Field in my Activity unless it is the only way.

Any help would be appreciated. Thanks in advance.


Solution

  • I have solution for this ,

    Button buttonTakePicture = (Button)dialog.findViewById(R.id.buttonTakePicture);
            buttonTakePicture.setTag(dialog);
            buttonTakePicture.setOnClickListener(this);
    

    and get the Dialog like this,

    @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.buttonTakePicture:
                    Dialog dialog = (Dialog) view.getTag();
                    if (dialog != null) {
                        view.setTag(null);
                        dialog.dismiss();
                    }
                    takePicture();
                    break;
            }
        }