Reputation: 45
Actually my issue is when i press the back button it shows a dialog
and also at the same time the application finished without any operation on key? Can any one solve this?
@Override
public void onBackPressed() {
super.onBackPressed();
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Really want to exit");
ab.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
ab.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Main.super.onBackPressed();
}
});
ab.create();
ab.show();
}
Upvotes: 1
Views: 82
Reputation: 35539
remove super.onBackPressed();
from method, keep it in onClick()
only
@Override
public void onBackPressed() {
super.onBackPressed(); //remove it
}
seems you are performing same operation in both buttons, you should remove Main.super.onBackPressed()
from negativeButton
ab.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
super.onBackPressed();
}
});
ab.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ab.dismiss();
}
});
Upvotes: 3
Reputation: 33238
Don't call super method of onBackPressed
.
@Override
public void onBackPressed() {
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Really want to exit");
ab.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
ab.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
ab.create();
ab.show();
}
Upvotes: 1
Reputation: 4335
You need to Remove, super.onBackPressed();
from onBackPressed()
. then your function should as,
@Override
public void onBackPressed() {
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Really want to exit");
ab.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
ab.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Main.super.onBackPressed();
}
});
ab.create();
ab.show();
}
Upvotes: 0
Reputation: 61
try this
@Override
public void onBackPressed() {
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Really want to exit");
ab.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
ab.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Main.super.onBackPressed();
}
});
ab.create();
ab.show();
}
Upvotes: 0