Android enable back button in webview

倖福魔咒の 提交于 2020-01-14 19:51:51

问题


I'm using the following code to display a webview in my Android app.

package com.company.myapp;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class ArticlesActivity extends Activity {

    /** Initialize the Google Analytics Tracker */
    GoogleAnalyticsTracker tracker;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
        WebView webview = new WebView(this);
        setContentView(webview); 
        setProgressBarVisibility(true); 
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        final Activity activity = this;
        tracker = GoogleAnalyticsTracker.getInstance();
        // Start the tracker, updating google every 20 seconds
        tracker.start((String) getText(R.string.analyticsID), 20, this);

        webview.setWebChromeClient(new WebChromeClient() { 
          public void onProgressChanged(WebView view, int progress) { 
            activity.setProgress(progress * 100 ); 
          } 
        }); 

        webview.setWebViewClient(new WebViewClient() { 
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
            }
        });
        webview.loadUrl("http://www.google.com");
    }
    @Override
    public void onResume() {
        tracker.trackPageView("ArticlesActivity");
        super.onResume();
    }
    @Override
    protected void onDestroy() {
      super.onDestroy();
      // Stop the tracker when it is no longer needed.
      tracker.stop();
    }
}

I would need to enable the back button to step back if history exists instead of just exiting the webview.

I've tried many different code examples such as this but can't get any to work. The app just shuts down when the back button is pressed.

Here's my code with the back button code but it just crashes the app when then back button is pressed:

package com.company.myapp;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class ArticlesActivity extends Activity {

    WebView webview;

    /** Initialize the Google Analytics Tracker */
    GoogleAnalyticsTracker tracker;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
        WebView webview = new WebView(this);
        setContentView(webview); 
        setProgressBarVisibility(true); 
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        final Activity activity = this;
        tracker = GoogleAnalyticsTracker.getInstance();
        // Start the tracker, updating google every 20 seconds
        tracker.start((String) getText(R.string.analyticsID), 20, this);

        webview.setWebChromeClient(new WebChromeClient() { 
          public void onProgressChanged(WebView view, int progress) { 
            activity.setProgress(progress * 100 ); 
          } 
        }); 

        webview.setWebViewClient(new WebViewClient() { 
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
            }
        });
        webview.loadUrl("http://www.google.com");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            webview.goBack();

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onResume() {
        tracker.trackPageView("ArticlesActivity");
        super.onResume();
    }
    @Override
    protected void onDestroy() {
      super.onDestroy();
      // Stop the tracker when it is no longer needed.
      tracker.stop();
    }
}

Could someone help me with a solution?


回答1:


Got it! Your problem in this line

WebView webview = new WebView(this);

Instead of using your member variable you are creating a variable inside function, and hence your member variable is null inside onKeyDown function.

Just replace it with

webview = new WebView(this);


来源:https://stackoverflow.com/questions/7400426/android-enable-back-button-in-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!