由于后退键破坏了我的应用程序并且所有数据都将丢失,我需要拦截它以询问用户这是否真的是他想要的。
我想到了以下结构:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
// ask user if he really wants to exit
// no --> return true;
// yes --> return super.onKeyDown(keyCode, event);
//manually entering either of the return values works fine
}
return super.onKeyDown(keyCode, event);
}
我想使用警报对话框实现的“询问用户”部分。我现在的问题是显示了警报对话框,但是 onKeyDown 方法在显示警报对话框时运行到最后,并且在警报对话框中我不知道如何告诉系统传递正确的返回值。
我想到的完整代码是
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Tile");
alertDialog.setMessage("data lost, are you sure?");
alertDialog.setButton(-1, getString(R.string.yes), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
return;
//I only can return without a boolean value here. }
});
alertDialog.setButton(-2, getString(R.string.no), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
alertDialog.show();
}
return super.onKeyDown(keyCode, event);
}
谢谢。