akh*_*3in 5 android onkeydown android-alertdialog
在代码中,当我按下后退按钮时,对话框会显示两次.有人可以告诉我如何只进行一次对话吗?
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();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 15
你的对话框出现了两次,因为它正在消耗两个来自后退键的事件,即按键和键盘向上...限制它们中的任何一个..
if (event.getAction() != KeyEvent.ACTION_DOWN)
{
/* Now call onBackPressed method here */
}
Run Code Online (Sandbox Code Playgroud)