4

Having problems getting the "Back" button to work in webview.

I'm not sure where in the code I should put the onKeyDown() part (currently under the last @Override)

Both mywebview.canGoBack() and mywebview.goBack() result in errors saying "mywebview cannot be resolved".

If I move the bracket after mywebview.setWebClient(...) all the way to the bottom, mywebview-error goes away, but then override, onKeyDown, return true, and return super result in all kind of errors.

Can anyone tell me what to do?

Code:

package com.sib;

import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class SiB extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sib);

        WebView mywebview = (WebView) findViewById(R.id.webview);
        mywebview.loadUrl("url");

        WebSettings webSettings = mywebview.getSettings();
        webSettings.setJavaScriptEnabled(true);

        mywebview.setWebViewClient(new WebViewClient());

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if ((keyCode == KeyEvent.KEYCODE_BACK) && mywebview.canGoBack()) {
            mywebview.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
Andre Dublin
  • 1,148
  • 1
  • 16
  • 34
user2076551
  • 41
  • 1
  • 2

2 Answers2

3

Make mywebview a class instance variable.

public class SiB extends Activity {
WebView mywebview;

Then make sure to not shadow it by taking out the declaration in onCreate() It should look like this:

mywebview = (WebView) findViewById(R.id.webview);
mywebview.loadUrl("url");

And based on what I can find, Gabe is right. onKeyDown() for back presses is only for API 4 and lower. onBackPressed() should work for everyting newer than API 4.

@Override
public void onBackPressed(){

    if (mywebview.canGoBack()) {
        mywebview.goBack();
        return;
    }
    super.onBackPressed();      
}
Community
  • 1
  • 1
A--C
  • 36,351
  • 10
  • 106
  • 92
2

onKeyDown doesn't work for back. You need to override onBackPressed.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127