Skip to content Skip to sidebar Skip to footer

Android Onkeylongpress When Webview Exists

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. What can I do to j

Solution 1:

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.

@OverridepublicvoidonBackPressed() {
    if(mWebView.canGoBack()) {
        mWebView.goBack();
    } else {
        super.onBackPressed();
    }
}

@OverridepublicbooleanonKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
            && !event.isCanceled() {
        super.onBackPressed();
        returntrue;
    }
    returnfalse;
}

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;
        returntrue;
    }
    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;
    }
    returnfalse;
}

Solution 2:

Take a look at this answer.

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

Hope it helps!

Post a Comment for "Android Onkeylongpress When Webview Exists"