Aug 15, 2011

More on WebView, override url loading

In the post android.webkit.WebView, we have implemented a very dummy web browser. But...once user click on a link, the default Android Browser will be opened to view the web page. To keep using our WebView to handle the event, we can implement a new class (MyWebViewClient) extends WebViewClient, and override the shouldOverrideUrlLoading() method, to take over the control when a new url is about to be loaded in the current WebView.

We have to call setWebViewClient() to set our WebViewClient to receive various notifications and requests.

package com.AndroidWebView;


import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class AndroidWebViewActivity extends Activity {

WebView webView;
final String DEFAULT_URL = "http://android-coding.blogspot.com/?m=1";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webView = (WebView)findViewById(R.id.webview);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl(DEFAULT_URL);

}

public class MyWebViewClient extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
}



next:
- Enable JavaScript and built-in zoom control of WebView

2 comments:

  1. when you load a html file, sometime it goes so slow. How can you make it smoothe or faster load.?
    Thanks in advance.

    ReplyDelete

Infolinks In Text Ads