开发者

Dialog shown twice when back button pressed

开发者 https://www.devze.com 2023-03-03 22:10 出处:网络
In code the dialog is shown two times when i press the back button. Can anyone please tell me how to get the dialog only once?

In code the dialog is shown two times when i press the back button. Can anyone please tell me how to get the dialog only once?

public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK))
        {
            onBackPressed();
        }
        return super.onKeyDown(keyCode, event);
         }

public void onBackPressed()
    {

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Do you want to save configuration?");
            builder.setPositiveButton
                           ("Yes", new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog, int id)
                {
                //here saveConfiguration is boolean type    
                    if (saveConfiguration()) 

                                              {
                        dialog.dismiss();
                        finish();

                    }
                    else
                    {
                        dialog.dismiss();
                    }

                }
            });
            builder.setNegativeB开发者_如何学Pythonutton("No", new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog, int id)
                {
                    dialog.dismiss();
                    finish();
                }
            });
            builder.show();
    }



}


Your dialog is coming twice because it is consuming two events from back key i.e. key down and key up .. restrict that to any one of them ..

             if (event.getAction() != KeyEvent.ACTION_DOWN)
 {

      /* Now call onBackPressed method here */
 }


onBackPressed() is a standart Activity method

What you are doing, is calling this method from onKeyDown manually, and then calling it again by delegataing event further via super.onKeyDown(keyCode, event) (which registers, that you pressed back and calls onBackPressed() automatically);

If you want to work with key back pressed event, thet either remove the onKeyDown method entierly and use only onBackPressed(), or rename your onBackPressed() to be something unique.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号