Tuesday, July 26, 2011

Confirm to Quit? Over-write the BACK key.

To over-write the BACK key, to prompt user for confirmation to quit instead of exiting directly, simply override the onBackPressed() method.

Confirm to Quit? Over-write the BACK key.

package com.exercise.AndroidConfirmQuit;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;

public class AndroidConfirmQuitActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

@Override
public void onBackPressed() {
// TODO Auto-generated method stub
//super.onBackPressed();
openQuitDialog();
}

private void openQuitDialog(){
AlertDialog.Builder quitDialog
= new AlertDialog.Builder(AndroidConfirmQuitActivity.this);
quitDialog.setTitle("Confirm to Quit?");

quitDialog.setPositiveButton("OK, Quit!", new OnClickListener(){

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}});

quitDialog.setNegativeButton("NO", new OnClickListener(){

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

}});

quitDialog.show();
}
}


2 comments:

Unknown said...

Thanks for the good post.. it helped..keep posting such useful posts

Turaç said...

Thank you for post