按下后退按钮时对话框显示两次
在代码中,当我按后退按钮时,对话框会显示两次。谁能告诉我如何只获得一次对话框?
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.setNegativeButton("No", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.dismiss();
finish();
}
});
builder.show();
}
}
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.setNegativeButton("No", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.dismiss();
finish();
}
});
builder.show();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的对话框出现两次,因为它消耗了后退键的两个事件,即按下键和按下键。将其限制为其中任何一个事件。
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 ..
onBackPressed() 是一个标准的 Activity 方法
什么您正在做的,是从 onKeyDown 手动调用此方法,然后通过 super.onKeyDown(keyCode, event) 进一步委托事件来再次调用它(它会注册,您按回并调用 onBackPressed() 自动地);
如果您想使用按键返回按下事件,则可以完全删除 onKeyDown 方法并仅使用 onBackPressed(),或者将 onBackPressed() 重命名为唯一的名称。
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.