Using DialogInterface's onClick() method

Viewed 26442

Here is my code to initialize the AlertDialog; buildexit is AlertDialog.Builder and exitalert is AlertDialog:

buildexit=new AlertDialog.Builder(this);
buildexit.setTitle("Exit?");
buildexit.setIcon(R.drawable.ic_action_warning);
buildexit.setMessage("Do you want to really exit?");
buildexit.setPositiveButton("Yes", this);
buildexit.setNegativeButton("No", this);
exitalert=buildexit.create();

I want to terminate the application using Activity.finish() method when the user clicks the "Yes" button, if "No" is click nothing should happen, I have also implemented the android.content.DialogInterface.OnClickListener interface, the method implemented is public void onClick(DialogInterface arg0, int arg1).
Thanks in advance.

5 Answers

With Kotlin and lambdas:

val alertDialog = AlertDialog.Builder(atakContext)
alertDialog.setTitle("Error!")
alertDialog.setMessage("Please ")

alertDialog.setPositiveButton("OK") { dialog: DialogInterface?, whichButton: Int ->
    //Do something
}
alertDialog.show()

You can use Lambda to shorten your code. JAVA

AlertDialog.Builder buildexit = new AlertDialog.Builder(this);
buildexit.create();
buildexit.setTitle("Exit?");
buildexit.setIcon(R.drawable.ic_action_warning);
buildexit.setMessage("Do you want to really exit?");
buildexit.setPositiveButton("Yes", (dialog, id) -> 
{
    this.finish();
});
buildexit.setNegativeButton("No", (dialog, id) -> 
{
    //Leaving this empty will close this onClick
});
buildexit.show();
Related