Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WebView - how to keep the user inside the app when they click on WebView links?

I had this command to keep the user still inside the app after they clicked links inside a webview. But I lost it and cannot seem to find what it is.

Could anyone please remind me what that command is? Thank you!

This is my code:

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);

    WebView webview = new WebView(this);
    webview.getSettings().setAppCacheEnabled(false);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.setInitialScale(1);
    webview.getSettings().setPluginState(PluginState.ON);

    webview.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });

    WebSettings webSettings = webview.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setBuiltInZoomControls(true);
    webSettings.setAllowContentAccess(true);
    webSettings.setEnableSmoothTransition(true);
    webSettings.setLoadsImagesAutomatically(true);
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setSupportZoom(true);
    webSettings.setUseWideViewPort(true);

    setContentView(webview);
    webview.loadUrl("http://www.stitcher.com/podcast/entrepreneuronfirecom/entrepreneur-on-fire-tim-ferriss-other-incredible-entrepreneurs");          
like image 440
Genadinik Avatar asked Jul 13 '13 11:07

Genadinik


1 Answers

To capture all clicks within the webView, you need to set a custom WebViewClient with shouldOverrideUrlLoading set to true

mWebView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
});

Without doing this, it will open in the browser.

http://developer.android.com/reference/android/webkit/WebViewClient.html#shouldOverrideUrlLoading(android.webkit.WebView, java.lang.String)

Give the host application a chance to take over the control when a new url is about to be loaded in the current WebView. If WebViewClient is not provided, by default WebView will ask Activity Manager to choose the proper handler for the url.

like image 154
Ken Wolf Avatar answered Sep 20 '22 22:09

Ken Wolf