Pergunta

i have developed an application that have one activity and i am going to code on exit pressed, i want do show dialogue box with three button when user pressed back button one for "yes" second for "home" and third for "exit" and i did it on on-back pressed method but i got some issue its not showing dialogue box if showing then its just flickering of dialogue box so what is reason behind it

my code is

public class MainActivity extends Activity {

private AlertDialog alertDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

}

@Override
public void onBackPressed() {
    super.onBackPressed();
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            MainActivity.this);

    alertDialogBuilder.setTitle("Alert Dialogue Box");

    alertDialogBuilder.setMessage("Are you sure?");

    alertDialogBuilder.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int id) {

                    Toast.makeText(getApplicationContext(),
                            "Positive", 1000).show();

                }

            });

    alertDialogBuilder.setNegativeButton("No",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                    dialog.cancel();

                    Toast.makeText(getApplicationContext(),
                            "You chose a negative answer",

                            Toast.LENGTH_LONG).show();

                }

            });

    alertDialogBuilder.setNeutralButton("Exit the app",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int id) {

                    Toast.makeText(getApplicationContext(), "exit",
                            1000).show();
                    MainActivity.this.finish();

                }

            });

    AlertDialog alertDialog = alertDialogBuilder.create();

    alertDialog.show();

}
Foi útil?

Solução

The code what you have written is fine.But this lines leads to Exception..

 super.onBackPressed();

which is finish your Activity so your Dialog is dismissed with Window leak Exception. So remove that line from your code.

Add this line to cancel touch on Outside.

alertDialog.setCanceledOnTouchOutside(false);

Outras dicas

you can set the AlertDialog.Builder in Dialog reference like :

Dialog dia = new AlertDialog.Builder(this)

and use dia to use SetCanceledOnTouchOutside method

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