gpt4 book ai didi

Android:拦截返回键

转载 作者:太空狗 更新时间:2023-10-29 12:56:27 25 4
gpt4 key购买 nike

由于后退键破坏了我的应用程序并且所有数据都将丢失,我需要拦截它以询问用户这是否真的是他想要的。

我想到了如下结构:

@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);
}

谢谢,A。

最佳答案

当用户按回键时,您的对话框就会出现。

现在已经处理了 onKeyDown,因此您返回 true。

您的对话框现在正在显示,

当你按下是时,你想模仿后退按钮,这就是finish() ;做

当你按下“否”时,你只是关闭对话框, Activity 继续

你会想要这个:

 @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)
{
finish(); // or yourContext.finish();
//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)
{
// do nothing dialog will dismiss
}
});

alertDialog.show();
return true; //meaning you've dealt with the keyevent
}
return super.onKeyDown(keyCode, event);
}

关于Android:拦截返回键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6289718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com