I have an app in which I have a WebView
where I display some websites. It works, clicking a link in the webpage goes to the next page in the website inside my a
I use something like this in my activities with WebViews:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Edit:
For this code to work, you need to add a field to the Activity
containing the WebView:
private WebView mWebView;
Initialize it in the onCreate()
method and you should be good to go.
mWebView = (WebView) findViewById(R.id.webView);
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
This is my solution. It works also in Fragment.
webView.setOnKeyListener(new OnKeyListener()
{
@Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
If using Android 2.2 and above (which is most devices now), the following code will get you what you want.
@Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
You should the following libraries on your class handle the onBackKeyPressed. canGoBack() checks whether the webview can reference to the previous page. If it is possible then use the goBack() function to reference the previous page (go back).
@Override
public void onBackPressed() {
if( mWebview.canGoBack()){
mWebview.goBack();
}else{
//Do something else. like trigger pop up. Add rate app or see more app
}
}
Focusing should also be checked in onBackPressed
@Override
public void onBackPressed() {
if (mWebview.isFocused() && mWebview.canGoBack()) {
mWebview.goBack();
} else {
super.onBackPressed();
finish();
}
}