如何处理回压(keyDown - 在以前的版本中)以显示退出应用程序的确认对话框?

发布于 2024-12-12 06:48:56 字数 733 浏览 0 评论 0原文

我已经通过重写 backPressed 方法制定了当用户按后退按钮时显示确认对话框的逻辑,但这意味着不寻常的行为。如果显示软输入键盘,则在后退键事件中,必须将其隐藏,并且其他后退键事件必须启动确认对话框。有办法实现这一点吗?也许通过检测软输入键盘是否打开并绕过确认对话框?

下面是一个代码示例来阐明这一点:

public boolean onKeyUp(int keyCode, KeyEvent event) 
{
    if (keyCode == KeyEvent.KEYCODE_BACK) 
    {
              //here is the mystery 
              if (soft keyboard is visible)
              {
                    return super.onKeyUp(keyCode, event);
              } else
              {
                                //method which shows the close dialog and close the application
                    onBackPressed();
                    return true;
              }
    }
              return super.onKeyUp(keyCode, event);
 }

I've made the logic for showing a confirm dialog when the user press back button by overriding backPressed method, but this implies an unusual behaviour. If soft input keyboard is shown, on back key event, it must be hidden and other back key event must launch the confirmation dialog. There is a way to achieve this? Maybe by detecting if soft input keyboard is up and bypass the confirmation dialog?

Here is a code sample to make this clear:

public boolean onKeyUp(int keyCode, KeyEvent event) 
{
    if (keyCode == KeyEvent.KEYCODE_BACK) 
    {
              //here is the mystery 
              if (soft keyboard is visible)
              {
                    return super.onKeyUp(keyCode, event);
              } else
              {
                                //method which shows the close dialog and close the application
                    onBackPressed();
                    return true;
              }
    }
              return super.onKeyUp(keyCode, event);
 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冬天旳寂寞 2024-12-19 06:48:56

如果显示软键盘,我认为 Activity 无法接收后退键事件。默认行为是后退键使软键盘消失。

View也可以屏蔽按键事件,简单的方法就是setOnKeyListener。确保您的 View 是可聚焦的,并且当它收到返回键事件时仅返回 true 。

if soft keyboard is shown ,I don't think Activity can receive back key event. the default behaviour is back key make soft keyboard disappear.

View also can block key event, the simple way is setOnKeyListener. make sure that your View is focusable and when it receive back key event just return true .

〃温暖了心ぐ 2024-12-19 06:48:56

隐藏软键盘的代码:

 InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

无论键盘是否显示,您都可以将此代码放在BackKeyPressed上

Code to hide the softkey pad :

 InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

you can put this code onBackKeyPressed no matter keyboard is showing or not

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文