androidbuttononclicklistenerandroid-alertdialogcustomdialog

Custom dialog not working with 'setOnClickListener' Android studio


I have a bit of weird situation - I have a made a custom dialog that opens when a button from the activity is clicked. The custom dialog contains a close button that when clicked closes the dialog and returns user to the activity. When I run the code as it is (shown below), instead of launching the custom dialog, it goes to the main activity (I think either reopens the app or somehow creates a imaginary intent for the main activity). However, when I remove/comment the code for the close button - highlighted as // === this code, everything works fine (the custom dialog opens) but the close button doesn't function. I am not sure what I am missing.

    // Global variable
    Button openDialog;

    // ======
    openDialog = (Button) findViewById(R.id.opendialog);
    openDialog.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {

            final Dialog cusomDialog = new Dialog(sellActivity.this);
            cusomDialog.setContentView(R.layout.customdialog);


            // === This code
            final Button close = (Button) findViewById(R.id.close);
            close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        cusomDialog.dismiss();

                    }
                });
            // === This code

            cusomDialog.show();


        }
    });

Can someone please shed some light on this, as I am really confused.


Solution

  • Initialize your View of Dialog inside Dialog:

    Replace this:

    final Button close = (Button) findViewById(R.id.close);
    

    With this:

    final Button close = (Button) cusomDialog.findViewById(R.id.close);