Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding a webview into another view

I have in my application 2 views:

a. res/layout/main.xml - a standard view with 1 button

b. res/layout/web_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
         <WebView android:id="@+id/webview"
            android:layout_height="fill_parent"
            android:layout_width="fill_parent" />
</LinearLayout>

When I click the button on the first view(a), it loads the webview(b) and loads an url:

// click on the "Browser" button in view a
public void goToWebView(View view) {
        setContentView(R.layout.web_view);
        WebView mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl("http://www.google.com");
    }

All that is working fine, the url load well but the browser is instantiated into its own view (a third one, not b itself) and my goal is to use the Webview to show some HTML code into my application, not outside of it, in a separate browser.

Anyboyd any idea?

This is done using API level8/Android 2.2.

Thanks for your help. Paul

like image 330
Paul Avatar asked Dec 05 '10 14:12

Paul


1 Answers

Actually I finally understood. Even if you programatically load the url with

mWebView.loadUrl("http://www.google.com");

you also have to mofify the default behaviour (which is opening an url in a new browser instance).
The previous code needs 2 enhancements.

// override default behaviour of the browser
private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }  

Then, set for the view which uses Webclient the new behaviour:

public void goToWebView(View view) {
        setContentView(R.layout.web_view);
        WebView mWebView = (WebView) findViewById(R.id.webview);
        // add the following line ----------
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl("http://www.google.com");
    }
like image 178
Paul Avatar answered Sep 29 '22 19:09

Paul