Pergunta

i want to display pop up when user press back button on home screen . but it is not working,and give no error. and i work on slider menu with this code

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

    AlertDialog.Builder build = new AlertDialog.Builder(this);
    build.setTitle("Confirmation");
    Log.d("aaaaa", "msg");
    build.setMessage("Are you sure, you want to exit ?");
    final AlertDialog alertDialog = build.create();
    alertDialog.show();
    build.setPositiveButton("Ha (Yes)", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            alertDialog.dismiss();
            finish();
        }
    });
    build.setNegativeButton("Na (No)", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            alertDialog.dismiss();
        }
    });
Foi útil?

Solução

you show the dialog before you set the yes/no buttons. You need to put alertDialog.show(); at the end. Also get rid of super.backPressed(). You do not need it since you are override this original functionality.

Outras dicas

Calling super.onBackPressed() means "treat the back button normally" (i.e., finish the activity).

Not calling it if you want to intercept it and show a dialog (as is the case) should be enough.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top