Enable back button in WebView

前端 未结 1 807
天命终不由人
天命终不由人 2020-12-03 23:14

I am just starting out with the Android SDK. I wanted to make a simple app with WebView that displays local web-pages only. I have used examples I have found on the net to m

1条回答
  •  -上瘾入骨i
    2020-12-03 23:30

    Override onKeyDown(params), check if the key pressed is back button ,check if the webview can navigate to previous page, if so naviagate to previous page. If there is no web page to display you can finish the actiivty

    You can use the below

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) { 
                //if Back key pressed and webview can navigate to previous page
            webView.goBack();
                // go back to previous page
            return true;
        }
        else
        {
            finish();
               // finish the activity
        }
        return super.onKeyDown(keyCode, event);
    }
    

    Edit:

    Remove the scrollview in xml layout. Try the below

    
    
    
    
    

    Edit:2

    Here's a sample that works. Tested on samsung galaxy s3

    activtiy_main.xml

    
    
    
    
    
    

    MainActivity

     public class MainActivity extends Activity {
     private WebView webView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
    
            setContentView(R.layout.activity_main);
            webView = (WebView) findViewById(R.id.wv);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.setWebChromeClient(new WebChromeClient() {
                   public void onProgressChanged(WebView view, int progress) {
                    MainActivity.this.setProgress(progress * 1000);
                   }
                 });
                 webView.setWebViewClient(new WebViewClient() {
                   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                     Toast.makeText(MainActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
                   }
                 });
    
                 webView.loadUrl("http://slashdot.org/");
    
    }   
    
    
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        else
        {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
    }
    

    0 讨论(0)
提交回复
热议问题