Skip to content Skip to sidebar Skip to footer

Finish An Activity When User Presses Positive Button On An Associated Dialogue

I want my activity, which shows a dialogue, to finish when a user clicks on the positive button of the dialogue. Is this possible. where do I place finish()? Code that calls the di

Solution 1:

Okay. I was able to finish the activity by putting getActivity().finish() under the onClick() of dialogue interface.

Solution 2:

you can use this code:

publicvoidshowMessageAlert(){
        runOnUiThread(new Runnable() {
            publicvoidrun() {
                AlertDialog.Builder builder = new AlertDialog.Builder(HomeScreen.this);

                builder.setTitle(ConfigClass.ALERT_TITLE);
                builder.setMessage(ConfigClass.MSG_ALERT);

                builder.setCancelable(true);
                builder.setInverseBackgroundForced(true);
                builder.setPositiveButton("I Accept",   new DialogInterface.OnClickListener() {
                    publicvoidonClick(DialogInterface arg0, int arg1) {
                        ActivityName.this.finish();
                    }
                });
                builder.setNegativeButton("I decline",  new DialogInterface.OnClickListener() {
                    publicvoidonClick(DialogInterface arg0, int arg1) {
                        //Do nothing
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            }
        });
}

Solution 3:

on click of positive button of the dialog call dialog.dismiss(); then finish();

Solution 4:

That's a Java problem with inner class visibility/scope. Inside the listener, this refers to the OnClickListener object and (luckily) it has no finish() method. To have it refer to the activity, either:

  • use simply finish(), without any prefix, if the listener is defined inside the activity. This way Java will look for the nearest enclosing object which defines a method named finish(), and it will find the Activity's one
  • use YouActivity.this.finish() to refer to the enclosing activity instance without any ambiguity (obviously this holds true if the listener is a (possibly anonymous) inner class of YourActivity
  • Call mActivity.finish() on some instance of your activity if it's defined in another file altogether (and maybe you'll have to cast the Context object)

Usually listeners are defined as anonymous inner classes inside activities, so calling finish() unprefixed should be enough, but you may want to use the A.this.finish() form if there are name collisions

Post a Comment for "Finish An Activity When User Presses Positive Button On An Associated Dialogue"