Alert Box in Android doesn't let me to click,

2020-05-06 13:39发布

问题:

I've a button upon clicking should display an alertdialog box containing just "OK" button and upon clicking should go to another activity. But this dialog box appears for a few seconds and goes to the activity without letting me click or confirm it. This is the code i've used

   public void onClick(View v) {

    AlertDialog.Builder alertbox = new AlertDialog.Builder(InsertData.this);

    alertbox.setMessage("Object Location Stored!");

    alertbox.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                // the button was clicked

                Intent a = new Intent(getApplicationContext(),MainMenu.class);
                startActivity(a);
            }

        });
        alertbox.show();

    }

Can anyone pls help me resolve this? Thanks in adv..

回答1:

I don't see what the problem is. A few days ago, I tried to include an AlertDialog myself. I saw that there are a lot of deprecated methods. I ended up using the code below. Try this if you like

AlertDialog ad=new AlertDialog.Builder(this).create();
        ad.setTitle(R.string.app_name);
        ad.setMessage("MESSAGE");
        ad.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }}); 
        ad.show();


回答2:

Heres an idea, lets see if your alertDialogs onClick is even being called. This will tell you if your problem is with the alert dialog or with something else. You should be able to copy and paste this into your app and then just call showAlertDialog(); from where ever you want. Post the code where your alertDialog is called from.

public void showAlertDialog()
{

         AlertDialog.Builder alertDialogBuilder = new AlertDialog
            .Builder(YourActivity.this);
     alertDialogBuilder.setTitle("Look at me!");
     alertDialogBuilder
            .setMessage("Im an alert dialog")
            .setCancelable(true)
            .setNegativeButton("Okay",new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialog,int id) 
                {

                    Toast.makeText(YourActivity.this, "Alert dialog onClick",   
                                    Toast.LENGTH_SHORT).show();   

                    dialog.dismiss();

                }
            }
        );

    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}