Android onKeyLongPress when webview exists

后端 未结 2 2062
星月不相逢
星月不相逢 2021-01-21 08:57

Regarding to that question and that question if you use onKeyDown and onKeyLongPress one need to use event.startTracking(); inside onKeyDown. But I use WebViews.

相关标签:
2条回答
  • 2021-01-21 09:29

    Take a look at this answer.

    Basically you use a handler in your onTouchEvent to detect a long press.

    Hope it helps!

    0 讨论(0)
  • 2021-01-21 09:44

    You need to override the onBackPressed() method instead of onKeyDown(), which is called from onKeyUp() post-Eclair unless the target SDK is set to lower than Eclair. Returning true from onKeyLongPress() will cause the event to be cancelled, and onBackPressed() won't be called.

    @Override
    public void onBackPressed() {
        if(mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
    
    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
                && !event.isCanceled() {
            super.onBackPressed();
            return true;
        }
        return false;
    }
    

    Edit: Actually you should override the onKeyUp() method instead to provide the same experience, and set a flag on the onKeyLongPress() call to check if it has been long pressed:

    private boolean isBackKeyLongPressed;
    
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
                && !event.isCanceled()) {
            if (!isBackKeyLongPressed && mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                onBackPressed();
            }
            isBackKeyLongPressed = false;
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            isBackKeyLongPressed = false;
        }
        return super.onKeyUp(keyCode, event);
    }
    
    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && !event.isCanceled()) {
            isBackKeyLongPressed = true;
        }
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题