Question

I created a custom dialog for my main activity with two buttons, Exit and Continue:

public class AgeConfirmationDialog extends Dialog {

    public AgeConfirmationDialog(Activity a) {
        super(a);    
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setCancelable(false);
        setContentView(R.layout.age_dialog);
        // .....
        // Find the View objects; checkboxes and buttons logic; SharedPreferences
        // .....
    }
    // .....
}

This is how the dialog is launched from the MainActivity:

AgeConfirmationDialog d = new AgeConfirmationDialog(this);
d.show();

This custom dialog pops out every time the main activity is started, and asks for a age confirmation. I don't want the users to close this dialog using the back button, so I added setCancelable(false) in the onCreate method. The Continue button is disabled until a checkbox is checked. If the Continue button is pressed, the dialog is dismissed - using setOnClickListener.

The problem is that I don't know how to dismiss that custom dialog AND finish the main activity when the Exit button is pressed.

Is it possible to do this from the AgeConfirmationDialog class by setting a View.OnClickListener on the Exit button?

Was it helpful?

Solution

change the code to something like this:

public class AgeConfirmationDialog extends Dialog {
    Activity mainActivity;

    public AgeConfirmationDialog(Activity a) {
        super(a);    
        this.mainActivity = a;
    }

    //in onClick method of finish-button
    public void onFinishClick(View v) {
        mainActivity.finish(); //finish activity
    }
}

OTHER TIPS

I don't know how to dismiss that custom dialog AND finish the main activity when the Exit button is pressed.

Then you just have to put in your ExitButton Click Listener:

finish();

For example:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setPositiveButton("Exit", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        }).create().show();

Do something in your onclicklistener of exit button. Like:

            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("EXIT", true);
            startActivity(intent);  

And your MainActivity do something like:

        if (getIntent().getBooleanExtra("EXIT", false)) {
        finish();
        }

What you basically do here is going to mainactivity which is your start activity with some key/value extra and check it in your mainactivity through getintent.

This is best process to exit application or you can use it also in logout.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top