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.
Take a look at this answer.
Basically you use a handler in your onTouchEvent
to detect a long press.
Hope it helps!
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;
}